﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.IO;
using System.Collections.Generic;
using System.Xml;
using System.Configuration;
using log4net;
using External.APICalling;
using BusinessRule.DTO;
using MES.DataGateway.DBUtility;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace MESWebService
{
    /// <summary>
    /// Service1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    public class TCMTOMESservice : System.Web.Services.WebService
    {
        ERPSendMESDataMethod erpMethod = new ERPSendMESDataMethod();
        TDMSendMESDataMethod tdmMethod = new TDMSendMESDataMethod();
        ZDSCSendMESDataMethod zdscMethod = new ZDSCSendMESDataMethod();
        TCGetMESActualMaterial MESActualMaterial = new TCGetMESActualMaterial();
        QmsToMesBusiness qms = new QmsToMesBusiness();
        private static object thisLock = new object();//创建对象锁 
        private const string m_strSuccess = "成功";
        private string XmlPath = "";
        private string DocPath = "";



        [WebMethod]
        public string UFC_Get_TCToMES_Service(string strMessage, Byte[] fileinstance)
        {
            //add:Wangjh 20181031 调用74的web服务
            // MES76WebService.TCMTOMESservice mes76 = new MES76WebService.TCMTOMESservice();
            //string strInfo = mes76.UFC_Get_TCToMES_Service(strMessage, fileinstance);
            //if (strInfo.Contains("失败")) 
            //{
            //    return strInfo;
            //}
            //

            LogHelp.SetConfig();
            string Path = "";
            GetConfigSetting();

            LogHelp.WriteLog("strMessage " + strMessage);
            XmlDocument myxml = new XmlDocument();
            myxml.LoadXml(strMessage);
            string strFileName = "";
            string strProcessName = "";
            string strProcessRev = "";

            XmlNode docnode = XMLParse.getNode(myxml, "/ReqMsg/document");
            strFileName = docnode.SelectSingleNode("document").InnerText;
            strProcessName = docnode.SelectSingleNode("process").InnerText;
            if (docnode.SelectSingleNode("processRev") != null)
            {
                strProcessRev = docnode.SelectSingleNode("processRev").InnerText;
            }

            if (strFileName.IndexOf(".xml") != -1)
            {
                Path = XmlPath + @"\" + strFileName;
            }
            else
            {
                Path = DocPath + @"\" + strProcessName + "$" + strProcessRev;
                Directory.CreateDirectory(Path);
                Path += @"\" + strFileName;
            }
            LogHelp.WriteLog(Path + "文件大小：" + fileinstance.Length.ToString().Trim());

            // 读取 BLOB 中数据，写入到文件中
            FileStream fs = null;
            try
            {
                if (File.Exists(Path)) //create:Wangjh 2017-6-26 增加是否为空判断
                {
                    fs = new FileStream(Path, FileMode.Append);
                }
                else
                {
                    fs = new FileStream(Path, FileMode.OpenOrCreate);
                }

                byte[] Buffer = fileinstance;
                fs.Write(Buffer, 0, Buffer.Length);
                fs.Flush();
            }
            catch (Exception ex)
            {
                LogHelp.WriteLog("接收数据失败");

                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>接收数据失败:" + ex.Message + "</document></ReqMsg>";
            }
            finally
            {
                fs.Close();
            }

            if (File.Exists(Path))
            {
                if (strFileName.IndexOf(".xml") != -1)
                {
                    LogHelp.WriteOrcale("PDMTOMES" + "@^" + "接收到xml" + "@^" + strFileName + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30

                    //yuxj20221011,因pdm传入的字节生成的xml存在格式错误，此处增加验证
                    //如果有错误，提示PDM重新发送
                    try
                    {
                        myxml = new XmlDocument();
                        myxml.Load(Path);
                        SaveBackXml(Path.Replace("DataXML", "backxml"), fileinstance);
                    }
                    catch (Exception ex)
                    {
                        LogHelp.WriteLog(strFileName + ":XML格式错误，请重新发送");
                        return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>接收数据失败，XML格式错误，请重新发送</document></ReqMsg>";
                    }
                }
                else
                {
                    LogHelp.WriteOrcale("PDMTOMES" + "@^" + "接收到附件" + strFileName + "@^" + strProcessName + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30
                }

                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>true</isSuccess></header><document>接收数据成功</document></ReqMsg>";
            }
            else
            {
                LogHelp.WriteLog("接收数据失败");
                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>接收数据失败</document></ReqMsg>";
            }

        }

        private void SaveBackXml(string Path, Byte[] fileinstance)
        {
            FileStream fs = null;
            try
            {
                if (File.Exists(Path)) //create:Wangjh 2017-6-26 增加是否为空判断
                {
                    fs = new FileStream(Path, FileMode.Append);
                }
                else
                {
                    fs = new FileStream(Path, FileMode.OpenOrCreate);
                }

                byte[] Buffer = fileinstance;
                fs.Write(Buffer, 0, Buffer.Length);
                fs.Flush();
            }
            catch (Exception ex)
            {
                LogHelp.WriteLog("接收数据失败");
            }
            finally
            {
                fs.Close();
            }
        }

        /// <summary>
        /// 给PDM的统一接口入口方法
        /// xml样例
        /*<?xml version="1.0" encoding="UTF-8"?>
<ReqMsg>
<header><sendSysName>APP_ERP</sendSysName>
<rcvSysName>APP_MES</rcvSysName>
<extConfig>
    <isReTry>false</isReTry>
</extConfig>
<FunName> ERP_Send_WebService </FunName>
</header>
<document>
    <mesFunName></mesFunName>
    <mesDocument>
		业务数据xml
    </mesDocument>
</document>
</ReqMsg>*/
        /// </summary>
        /// <param name="strMessage"></param>
        /// <returns></returns>
        [WebMethod]
        public string PDM_Send_WebService(string strMessage, Byte[] fileinstance)
        {
            LogHelp.SetConfig();
            XmlDocument myxml = new XmlDocument();
            myxml.LoadXml(strMessage);
            //获取内容
            string mesFun = myxml.SelectSingleNode("ReqMsg/document/mesFunName").InnerText;
            LogHelp.WriteLog("PDM_Send_WebService" + "_" + mesFun + "接收到的xml是:" + strMessage);//接收日志
            try
            {
                XmlNode mesDoc = myxml.SelectSingleNode("ReqMsg/document/mesDocument");
                string strMsg = "";//返回参数
                switch (mesFun)
                {
                    case "PDM_DesignChange_Service":
                        strMsg = PDM_DesignChange_Service(mesDoc);
                        break;
                    default:
                        strMsg = qms.RespMsg("false", "接收数据失败", "E", "系统服务找不到对应的【" + mesFun + "】方法");
                        break;
                }
                LogHelp.WriteOrcale("PDM_Send_WebService" + "_" + mesFun + "@^" + strMsg + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30
                LogHelp.WriteLog("PDM_Send_WebService" + "_" + mesFun + "处理结果：" + strMsg);//处理结果日志
                return strMsg;
            }
            catch (Exception ex)
            {
                LogHelp.WriteOrcaleError("PDM_Send_WebService" + "_" + mesFun + "@^" + ex.Message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()), ex);//add:Wangjh 2017-8-30
                LogHelp.WriteError(ex.Message + strMessage, ex);
                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document><![CDATA[<TETTYP><RTYPE>E</RTYPE><RTMSG>" + ex.Message + "</RTMSG></TETTYP>]]></document></ReqMsg>";
            }
        }

        private void GetConfigSetting()
        {
            XmlPath = ConfigurationManager.AppSettings["DataXmlPath"];
            DocPath = ConfigurationManager.AppSettings["AccessoriesPath"];
        }

        #region  给ERP的统一接口入口方法，适用于访问量不大的接口,根据字段方法传参判断调用不同方法
        /// <summary>
        /// 给ERP的统一接口入口方法，适用于访问量不大的接口 
        /// add:Wangjh 20221207
        /// </summary>
        /// <param name="strXML"></param>
        /// <returns></returns>
        /* xml样例
<?xml version="1.0" encoding="UTF-8"?>
<header><sendSysName>APP_ERP</sendSysName>
<rcvSysName>APP_MES</rcvSysName>
<extConfig>
  <isReTry>false</isReTry>
</extConfig>
<FunName> ERP_Send_WebService </FunName>
</header>
<document>
<![CDATA[
<root>
	<mesFunName></mesFunName>
	<mesDocument>
		
	</mesDocument>
</root>
]]>
</document>
</ReqMsg>
        */
        [WebMethod]
        public string ERP_Send_WebService(string strMessage)
        {
            LogHelp.SetConfig();
            XmlDocument myxml = new XmlDocument();
            myxml.LoadXml(strMessage);
            //获取内容
            myxml.LoadXml(myxml.SelectSingleNode("ReqMsg/document").InnerText);
            string mesFun = myxml.SelectSingleNode("root/mesFunName").InnerText;
            LogHelp.WriteLog("ERP_Send_WebService" + "_" + mesFun + "接收到的xml是:" + strMessage);//接收日志
            try
            {
                XmlNode mesDoc = myxml.SelectSingleNode("root/mesDocument");
                string strMsg = "";//返回参数
                switch (mesFun)
                {
                    case "ERPWorkCenterFun":
                        strMsg = ERPWorkCenterFun(mesDoc);
                        break;
                    default:
                        break;
                }
                LogHelp.WriteOrcale("ERP_Send_WebService" + "_" + mesFun + "@^" + strMsg + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30
                LogHelp.WriteLog("ERP_Send_WebService" + "_" + mesFun + "处理结果：" + strMsg);//处理结果日志
                return strMsg;
            }
            catch (Exception ex)
            {
                LogHelp.WriteOrcaleError("ERP_Send_WebService" + "_" + mesFun + "@^" + ex.Message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()), ex);//add:Wangjh 2017-8-30
                LogHelp.WriteError(ex.Message + strMessage, ex);

                return @"<?xml version='1.0' encoding='utf-8'?><RespMsg><header><sysName>APP_MES</sysName><isSuccess>true</isSuccess><message></message></header><document><![CDATA[<TETTYP><RTYPE>E</RTYPE><RTMSG>" + ex.Message + "</RTMSG></TETTYP>]]></document></RespMsg>";
                //return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>" + ex.Message + "</document></ReqMsg>";

            }


        }

        #endregion

        #region erp工作中心接口方法 add:Wangjh 20221213
        string ERPWorkCenterFun(XmlNode mesDoc)
        {
            Dictionary<string, string> para = new Dictionary<string, string>();
            para.Add("workcenterCode", mesDoc.SelectSingleNode("WORKCENTERCODE").InnerText);
            para.Add("description", mesDoc.SelectSingleNode("WORKCENTERNAME").InnerText);
            para.Add("factoryCode", mesDoc.SelectSingleNode("FACTORYCODE").InnerText);
            para.Add("factoryName", mesDoc.SelectSingleNode("FACTORYNAME").InnerText);

            //存储数据
            string strSql = string.Format(@"declare id  varchar2(50);
begin
  select nvl(max(Erpworkcentercodeid),'0') into id from ERPWorkcenterCode ew where ew.workcentercode='{0}';
  dbms_output.put_line(id);
  if id <> '0' then
    update ERPWorkcenterCode ew set ew.description='{1}',ew.factorycode='{2}',ew.factoryname='{3}',ew.LastChangeDate=sysdate
    where ew.workcentercode='{0}';
  else
    insert into ERPWorkcenterCode (Erpworkcentercodeid,Workcentercode,Description,Factorycode,Factoryname,CreateDate,LastChangeDate)
    values(sys_guid(),'{0}','{1}','{2}','{3}',sysdate,sysdate);
  end if;
  commit;
end;", para["workcenterCode"], para["description"], para["factoryCode"], para["factoryName"]);
            var oldWorkcenterName = OracleHelper.GetSingle(string.Format(@"select ew.Description from ERPWorkcenterCode ew where ew.workcentercode='{0}'", para["workcenterCode"]));
            if (OracleHelper.ExecuteSql(strSql) > 0)
            {
                //InsertOrUpdateMesWorkCenterByERP(mesDoc.SelectSingleNode("factoryName").InnerText, mesDoc.SelectSingleNode("description").InnerText, oldWorkcenterName == null ? "" : oldWorkcenterName.ToString());
            }
            return @"<?xml version='1.0' encoding='utf-8'?><RespMsg><header><sysName>APP_MES</sysName><isSuccess>true</isSuccess><message></message></header><document><![CDATA[<TETTYP><RTYPE>S</RTYPE><RTMSG>" + para["workcenterCode"] + "ERP工作中心接收成功" + "</RTMSG></TETTYP>]]></document></RespMsg>";
            //return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>true</isSuccess></header><document>" + para["workcenterCode"] + "ERP工作中心接收成功" + "</document></ReqMsg>";

        }
        void InsertOrUpdateMesWorkCenterByERP(string factoryName, string workcenterDes, string workcenterName)
        {
            try
            {
                var sqlStr = @"SELECT w.WORKCENTERID,w.WORKCENTERNAME,w.DESCRIPTION,f.FACTORYNAME,w.* FROM WORKCENTER w 
                        LEFT JOIN FACTORY f ON f.FACTORYID =w.FACTORYID
                        WHERE f.FACTORYNAME ='{0}' AND w.WORKCENTERNAME ='{1}'";
                DataTable dt = OracleHelper.Query(string.Format(sqlStr, factoryName, workcenterName)).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    OracleHelper.ExecuteSql(string.Format(@"update WORKCENTER w set w.WORKCENTERNAME='{0}',w.DESCRIPTION='{0}' where w.WORKCENTERID='{1}'", workcenterDes, dt.Rows[0]["WORKCENTERID"]));
                }
                else
                {
                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    string msg = string.Empty;
                    dic.Add("workcenterName", workcenterDes);
                    dic.Add("factoryName", factoryName);
                    dic.Add("Description", workcenterDes);
                    dic.Add("Notes", "ERP工区备注");
                    erpMethod.SaveWorkCenterData(dic, ref msg);
                }
            }
            catch (Exception ex)
            {

            }
        }
        #endregion

        /// <summary>
        /// QMS质量调用MES统一接口入口方法
        /// </summary>
        /// <param name="strMessage"></param>
        /// <returns></returns>
        [WebMethod]
        public string QMS_Send_WebService(string strMessage)
        {
            LogHelp.SetConfig();
            XmlDocument myxml = new XmlDocument();
            myxml.LoadXml(strMessage);
            //获取内容
            myxml.LoadXml(myxml.SelectSingleNode("ReqMsg/document").InnerText);
            string mesFun = myxml.SelectSingleNode("root/mesFunName").InnerText;
            LogHelp.WriteLog("QMS_Send_WebService" + "_" + mesFun + "接收到的xml是:" + strMessage);//接收日志
            try
            {
                XmlNode mesDoc = myxml.SelectSingleNode("root/mesDocument");
                string strMsg = "";//返回参数
                switch (mesFun)
                {
                    case "sendArmyCheckList"://军检项目推送接口 add by longb 2022-12-27
                        strMsg = qms.sendArmyCheckList(mesDoc);
                        break;
                    case "receiveIqsResult"://理化试验结果集成接口(返回) add by longb 2023-03-06
                        strMsg = qms.receiveIqsResult(mesDoc, strMessage);
                        break;
                    case "productsMilitaryResults"://产品军检结果接口
                        strMsg = qms.QMSArmyInstoreResult(mesDoc);
                        break;
                    case "QMS_Send_SpecMilitaryCheckInfoResult_Service"://工序军检结果接口 add by zhangrj 2022-12-26
                        strMsg = qms.QMS_Send_SpecMilitaryCheckInfoResult_Service(mesDoc);
                        break;
                    case "QMS_Send_DealFaultBillResult_Service"://2.5排故单审理结果接口 add by longb 2023-04-13
                        strMsg = qms.DealFaultBillResult(mesDoc);
                        break;
                    case "QMS_Send_DealFaultBillResolveResult_Service"://2.7排故单处理结果审理接口 add by longb 2023-04-13
                        strMsg = qms.DealFaultBillResolveResult(mesDoc);
                        break;
                    case "ZSGJCheckSubmitBillResult"://2.9故检提交单审理结果接口 add by longb 2023-04-13
                        strMsg = qms.ZSGJCheckSubmitBillResult(mesDoc);
                        break;
                    case "QMS_Send_ExchangeBillResult_Service"://2.11周转/串件审理结果接口 add by longb 2023-04-13
                        strMsg = qms.ExchangeBillResult(mesDoc);
                        break;
                    #region MyRegion
                    case "qaProblemHearResultNotify"://系统质量问题审理结果接口 modify by longb 2023-04-12
                        strMsg = qms.qaProblemHearResultNotify(mesDoc);
                        break;
                    case "firstThingAuth"://首件鉴定目录接口 modify by longb 2023-04-12
                        strMsg = qms.firstThingAuth(mesDoc);
                        break;
                    case "firstThingAuthDirControlPointRelease"://首件鉴定控制点解除接口 modify by longb 2023-04-12
                        strMsg = qms.firstThingAuthDirControlPointRelease(mesDoc);
                        break;
                    case "pushQaProductReviewDir"://质量评审目录接口 modify by longb 2023-04-12
                        strMsg = qms.pushQaProductReviewDir(mesDoc);
                        break;
                    case "qaProductReviewDirControlPointRelease"://产品质量评审控制点解除接口 modify by longb 2023-04-12
                        strMsg = qms.qaProductReviewDirControlPointRelease(mesDoc);
                        break;
                    case "pushCraftReviewDir"://工艺评审控制点接口 modify by longb 2023-04-12
                        strMsg = qms.pushCraftReviewDir(mesDoc);
                        break;
                    case "craftReviewDirControlPointRelease"://工艺评审控制点解除接口 modify by longb 2023-04-12
                        strMsg = qms.craftReviewDirControlPointRelease(mesDoc);
                        break;
                    #endregion
                    case "qmsSendCheckInfo"://1.1检验信息接口 add by longb 2024-12-18
                        strMsg = qms.qmsSendCheckInfo(mesDoc);
                        break;
                    case "qmsToMesAPI"://新QMS理化调用MES接口
                        strMsg = qms.newQmsToMesAPI(strMessage, myxml.SelectSingleNode("root/qmsDocument"));
                        break;
                    case "qmsSendReturnInbound"://退料退库申请检验结果接口 add by longb 2025-10-23
                        strMsg = qms.qmsSendReturnInbound(mesDoc);
                        break;
                    default:
                        strMsg = qms.RespMsg("false", "接收数据失败", "E", "系统服务找不到对应的【" + mesFun + "】方法");
                        break;
                }
                LogHelp.WriteOrcale("QMS_Send_WebService" + "_" + mesFun + "@^" + strMsg + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"").Replace("{", "{{").Replace("}", "}}")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30
                LogHelp.WriteLog("QMS_Send_WebService" + "_" + mesFun + "处理结果：" + strMsg);//处理结果日志
                return strMsg;
            }
            catch (Exception ex)
            {
                LogHelp.WriteOrcaleError("QMS_Send_WebService" + "_" + mesFun + "@^" + ex.Message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()), ex);//add:Wangjh 2017-8-30
                LogHelp.WriteError(ex.Message + strMessage, ex);
                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document><![CDATA[<TETTYP><RTYPE>E</RTYPE><RTMSG>" + ex.Message + "</RTMSG></TETTYP>]]></document></ReqMsg>";

            }
        }


        #region  MES和ERP订单信息集成接口
        [WebMethod]
        public string ERP_Send_Order_Service(string strMessage)
        {
            LogHelp.SetConfig();
            try
            {
                //  LogHelp .WriteLog("ERP发送信息" + strMessage);
                XmlDocument mydoc = XMLParse.getDocument(strMessage);
                XmlNode docnode = XMLParse.getNode(mydoc, "/ReqMsg/document");
                Dictionary<string, string> strList = new Dictionary<string, string>();
                LogHelp.WriteLog(docnode.ChildNodes[1].InnerText);

                string InnerText = docnode.SelectSingleNode("AUFK-AUART").InnerText;//生产订单类型名称代号
                strList.Add("OrderType", InnerText);
                InnerText = docnode.SelectSingleNode("T003P-TXT").InnerText;// docnode.ChildNodes[1].InnerText;//生产订单类型名称
                strList.Add("OrderTypeDes", InnerText);
                InnerText = docnode.SelectSingleNode("AFKO-AUFNR").InnerText;// docnode.ChildNodes[2].InnerText;//生产订单号
                strList.Add("mfgordername", InnerText);
                InnerText = docnode.SelectSingleNode("AFKO-PLNBEZ").InnerText;// docnode.ChildNodes[3].InnerText;//件号
                string productName = InnerText;
                //件号：productname的erp和tc大小写不一致的情况转换处理，erp都是大写，tc可能小写
                erpMethod.erpAndTcProductNameHandle(ref productName);

                strList.Add("productName", productName);
                InnerText = docnode.SelectSingleNode("MAKT-MAKTX").InnerText;//docnode.ChildNodes[4].InnerText;//件号名称
                strList.Add("Description", InnerText);
                InnerText = docnode.SelectSingleNode("AFKO-GAMNG").InnerText;// docnode.ChildNodes[5].InnerText;//数量
                strList.Add("qty", InnerText);
                InnerText = docnode.SelectSingleNode("AFKO-GSTRP").InnerText;// docnode.ChildNodes[6].InnerText;//开始日期
                strList.Add("PlannedStartDate", InnerText);
                InnerText = docnode.SelectSingleNode("AFKO-GLTRP").InnerText;// docnode.ChildNodes[7].InnerText;//完成日期
                strList.Add("PlannedCompletionDate", InnerText);

                //add:Wangjh 20220701 增加订单状态
                //if (docnode.SelectNodes("JEST-STATUS").Count > 0)
                //{
                //    strList.Add("OrderStatus", docnode.SelectSingleNode("JEST-STATUS").InnerText);
                //    if (strList["OrderStatus"] == "TECO")
                //    {
                //        strList["OrderStatus"] = "关闭";
                //    }
                //    else if (strList["OrderStatus"] == "PAUSE")
                //    {
                //        strList["OrderStatus"] = "暂停";
                //    }
                //    else if (strList["OrderStatus"] == "REL")
                //    {
                //        strList["OrderStatus"] = "下达";
                //    }
                //    else if (strList["OrderStatus"] == "DLV")
                //    {
                //        strList["OrderStatus"] = "完全交货";
                //    }
                //    else if (strList["OrderStatus"] == "ELSE")
                //    {
                //        strList["OrderStatus"] = "其他";
                //    }
                //}
                strList["OrderStatus"] = "打开";//默认打开
                string pdmProductName = "";
                try
                {
                    // PDM原始零件号 add:Wangjh 20180108
                    pdmProductName = docnode.SelectSingleNode("ZPPT_PDM-MATNR_O").InnerText;
                    if ((!string.IsNullOrWhiteSpace(pdmProductName)))//存在则表示当前推的是组别件号
                    {
                        //创建组别件号并挂对应pdmProductName的工艺
                        string strMsg = "";
                        strList["ProductType"] = "组别件";
                        strList["Description"] = "螺母";
                        strList["PdmProductName"] = pdmProductName;

                        strMsg = erpMethod.CopyOrUpdateProductByProduct(pdmProductName, strList);

                        if (!string.IsNullOrWhiteSpace(strMsg))
                        {
                            LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + "订单" + strList["mfgordername"] + "接收失败" + strMsg + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30
                            LogHelp.WriteLog("订单" + strList["mfgordername"] + "接收失败" + strMsg + strMessage);
                            return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>" + strList["mfgordername"] + "接收订单数据失败" + strMsg + "</document></ReqMsg>";
                        }

                    }
                }
                catch (Exception ex) { }
                string mfgordername = strList["mfgordername"];
                DataTable _AttributeTable = new DataTable();
                _AttributeTable = new DataTable();
                _AttributeTable.Columns.Add("Name");
                _AttributeTable.Columns.Add("AttributeValue");
                DataRow _AttributeRow;

                _AttributeRow = _AttributeTable.NewRow();
                _AttributeRow["Name"] = "MRP控制者";
                _AttributeRow["AttributeValue"] = docnode.SelectSingleNode("AUFK-DISPO1").InnerText;
                _AttributeTable.Rows.Add(_AttributeRow);

                _AttributeRow = _AttributeTable.NewRow();
                _AttributeRow["Name"] = "MRP控制者名称";
                _AttributeRow["AttributeValue"] = docnode.SelectSingleNode("TO24D-DSNAM").InnerText;
                _AttributeTable.Rows.Add(_AttributeRow);

                _AttributeRow = _AttributeTable.NewRow();
                _AttributeRow["Name"] = "分厂代号";
                InnerText = docnode.SelectSingleNode("AFKO-FEVOR").InnerText.Replace("618", "603");
                _AttributeRow["AttributeValue"] = InnerText;
                _AttributeTable.Rows.Add(_AttributeRow);
                string factory = erpMethod.GetFacorybyCode(InnerText);
                string factoryCode = InnerText;
                //工装工具公司:工装件materialcode和productName不一致，需要复制一份product出来name为AFKO-PLNBEZ值。
                string gzProduct = "";//工装mes中的件号
                if (InnerText == "604")
                {
                    DataTable jbstDt = erpMethod.GetJBSTData(productName);
                    if (jbstDt.Rows.Count > 0)
                    {
                        //pdmProductName = jbstDt.Rows[0]["productname"].ToString();
                        //strList["MaterialCode"] = pdmProductName;
                        //strList["ProductType"] = "工装虚拟件";

                        //string strMsg = "";
                        //strMsg = erpMethod.CopyOrUpdateProductByProduct(pdmProductName, strList);
                        //if (!string.IsNullOrWhiteSpace(strMsg))
                        //{
                        //    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + "订单" + strList["mfgordername"] + "接收失败" + strMsg + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30
                        //    LogHelp.WriteLog("订单" + strList["mfgordername"] + "接收失败" + strMsg + strMessage);
                        //    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>" + strList["mfgordername"] + "接收订单数据失败" + strMsg + "</document></ReqMsg>";
                        //}       

                        gzProduct = jbstDt.Rows[0]["productname"].ToString();
                        strList["productName"] = gzProduct;

                    }
                }

                //叶片分厂：：锻件订单，AFKO-PLNBEZ值为materialcode,和productName不一致,需要复制一份product出来name为AFKO-PLNBEZ值。
                if (InnerText == "608" || InnerText == "601")//新增机匣厂
                {
                    var productDt = erpMethod.GetProductNameByMaterialCode(productName);
                    if (productDt.Rows.Count > 0)
                    {
                        strList["ProductType"] = "叶片锻件虚拟件";
                        pdmProductName = productDt.Rows[0]["productname"].ToString();
                        strList["PdmProductName"] = pdmProductName;
                        strList["MaterialCode"] = pdmProductName;
                        string strMsg = "";
                        strMsg = erpMethod.CopyOrUpdateProductByProduct(pdmProductName, strList);
                        if (!string.IsNullOrWhiteSpace(strMsg))
                        {
                            LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + "订单" + strList["mfgordername"] + "接收失败" + strMsg + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30
                            LogHelp.WriteLog("订单" + strList["mfgordername"] + "接收失败" + strMsg + strMessage);
                            return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>" + strList["mfgordername"] + "接收订单数据失败" + strMsg + "</document></ReqMsg>";
                        }
                    }


                    //if (string.IsNullOrWhiteSpace(erpMethod.GetProductDefaultRev(productName)))
                    //{                       
                    //    if (productDt.Rows.Count > 0)
                    //    {
                    //        var productRow = productDt.Rows[0];

                    //        Dictionary<string, string> para = new Dictionary<string, string>() {
                    //            { "PdmProductName", productRow["productname"].ToString() },
                    //            { "Revision", productRow["productrevision"].ToString() }, { "ProductType", productRow["producttypename"].ToString() },
                    //            { "productName",productName }, { "MaterialCode",productRow["productname"].ToString() }
                    //        };

                    //        erpMethod.CopyProduct(para, ref strMessage);
                    //    }
                    //}

                }
                //
                _AttributeRow = _AttributeTable.NewRow();
                _AttributeRow["Name"] = "分厂名称";
                InnerText = docnode.SelectSingleNode("T024F-TXT_FEVOR").InnerText;
                _AttributeRow["AttributeValue"] = InnerText;
                _AttributeTable.Rows.Add(_AttributeRow);

                //增加父订单号属性信息
                _AttributeRow = _AttributeTable.NewRow();
                _AttributeRow["Name"] = "父订单号";
                try
                {
                    InnerText = docnode.SelectSingleNode("AFKO-MAUFNR").InnerText;
                }
                catch (Exception ex) { InnerText = ""; }
                _AttributeRow["AttributeValue"] = InnerText;
                _AttributeTable.Rows.Add(_AttributeRow);

                //_AttributeRow = _AttributeTable.NewRow();
                //_AttributeRow["Name"] = "组别件号";
                //if (string.IsNullOrWhiteSpace(pdmProductName))//判断是否有源零件号(父零件号)
                //{
                //    _AttributeRow["AttributeValue"] = "";
                //}
                //else {
                //    _AttributeRow["AttributeValue"] = productName;
                //}
                //_AttributeTable.Rows.Add(_AttributeRow);

                _AttributeRow = _AttributeTable.NewRow();
                if (!string.IsNullOrWhiteSpace(pdmProductName))//判断是否有源零件号(父零件号)
                {
                    _AttributeRow["Name"] = "源件号";
                    _AttributeRow["AttributeValue"] = pdmProductName;
                    _AttributeTable.Rows.Add(_AttributeRow);
                }
                //

                //add:Wangjh 20180528 装饰增加发动机号
                try
                {
                    string ZSERNUM = docnode.SelectSingleNode("ZSERNUM").InnerText;// 发动机号
                    if (!string.IsNullOrWhiteSpace(ZSERNUM))
                    {
                        _AttributeRow = _AttributeTable.NewRow();
                        _AttributeRow["Name"] = "发动机";
                        _AttributeRow["AttributeValue"] = ZSERNUM;
                        _AttributeTable.Rows.Add(_AttributeRow);
                    }
                }
                catch (Exception ex) { }
                //

                //add:Wangjh 20180727 装饰增加原发动机订单号
                try
                {
                    string ZAUFNR = docnode.SelectSingleNode("ZAUFNR").InnerText;// 原发动机订单号
                    if (!string.IsNullOrWhiteSpace(ZAUFNR))
                    {
                        _AttributeRow = _AttributeTable.NewRow();
                        _AttributeRow["Name"] = "原发动机订单号";
                        _AttributeRow["AttributeValue"] = ZAUFNR;
                        _AttributeTable.Rows.Add(_AttributeRow);
                    }
                }
                catch (Exception ex) { }
                //

                strList.Add("Factory", factory);


                //机型,主制工区，MRP区域，优先级字段增加 add:Wangjh 20221126
                if (docnode.SelectSingleNode("EXTWG") != null)//机型
                {
                    if (!string.IsNullOrWhiteSpace(docnode.SelectSingleNode("EXTWG").InnerText))
                    {
                        strList.Add("ProductFamilyName", docnode.SelectSingleNode("EXTWG").InnerText);
                    }
                }

                if (docnode.SelectSingleNode("PLANER") != null)//主制工区
                {
                    if (!string.IsNullOrWhiteSpace(docnode.SelectSingleNode("PLANER").InnerText))
                    {
                        strList.Add("WorkcenterName", docnode.SelectSingleNode("PLANER").InnerText);
                    }
                }

                if (docnode.SelectSingleNode("BERID") != null)//mrp区域
                {
                    if (!string.IsNullOrWhiteSpace(docnode.SelectSingleNode("BERID").InnerText))
                    {
                        strList.Add("MRPArea", docnode.SelectSingleNode("BERID").InnerText);
                    }
                }

                if (docnode.SelectSingleNode("APRIO") != null)//优先级
                {
                    if (!string.IsNullOrWhiteSpace(docnode.SelectSingleNode("APRIO").InnerText))
                    {
                        strList.Add("Priority", docnode.SelectSingleNode("APRIO").InnerText);
                    }
                }

                if (docnode.SelectSingleNode("ZZJHY") != null)//分厂计划员
                {
                    if (!string.IsNullOrWhiteSpace(docnode.SelectSingleNode("ZZJHY").InnerText))
                    {
                        strList.Add("ZZJHY", docnode.SelectSingleNode("ZZJHY").InnerText);
                    }
                }
                if (docnode.SelectSingleNode("ZSFJJ") != null)//是否军检
                {
                    if (!string.IsNullOrWhiteSpace(docnode.SelectSingleNode("ZSFJJ").InnerText))
                    {
                        strList.Add("ZSFJJ", docnode.SelectSingleNode("ZSFJJ").InnerText);
                    }
                }
                if (docnode.SelectSingleNode("ZSFQT") != null)//物料是否齐套，字段待定 add:wangjh 20241119
                {
                    if (!string.IsNullOrWhiteSpace(docnode.SelectSingleNode("ZSFQT").InnerText))
                    {
                        strList.Add("IsCompProduct", docnode.SelectSingleNode("ZSFQT").InnerText);
                    }
                }
                if (docnode.SelectSingleNode("ZHBMODEL") != null)//合并机型 add by longb 2025-05-27
                {
                    if (!string.IsNullOrWhiteSpace(docnode.SelectSingleNode("ZHBMODEL").InnerText))
                    {
                        strList.Add("ZHBMODEL", docnode.SelectSingleNode("ZHBMODEL").InnerText);
                    }
                    else
                    {
                        strList.Add("ZHBMODEL", "");
                    }
                }

                if (docnode.SelectSingleNode("LGORT") != null)//库存地 add by zhangrj 2025-10-20
                {
                    if (!string.IsNullOrWhiteSpace(docnode.SelectSingleNode("LGORT").InnerText))
                    {
                        strList.Add("LGORT", docnode.SelectSingleNode("LGORT").InnerText);
                    }
                }


                string message = erpMethod.SaveMfgorder(strList, _AttributeTable, null);

                #region 机匣测试服务器写入 add:Wangjh 20170925

                //if (factory.Contains("机匣")) 分发取消
                //{
                //    string remoteServicer = ConfigurationManager.AppSettings["JXServerHost"];
                //    strList["Factory"] = "";
                //    string JX_message = erpMethod.SaveMfgorder(strList, _AttributeTable, remoteServicer);
                //    message = JX_message;
                //    remoteServicer = null;
                //}

                #endregion


                if (message == "成功")
                {
                    if (factoryCode == "604" && !string.IsNullOrWhiteSpace(gzProduct)) //工装工具,需要把订单和批次关联
                    {
                        erpMethod.UpdateContainerMfgorder(mfgordername, strList["productName"], strList["OrderType"]);
                    }
                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + "订单" + mfgordername + "接收成功" + message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30
                    LogHelp.WriteLog("订单" + mfgordername + "接收成功" + strMessage);
                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>true</isSuccess></header><document>" + mfgordername + "接收订单数据成功</document></ReqMsg>";
                }
                else
                {
                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + "订单" + mfgordername + "接收失败" + message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30
                    LogHelp.WriteLog("订单" + mfgordername + "接收失败" + message + strMessage);
                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>" + mfgordername + "接收订单数据失败" + message + "</document></ReqMsg>";
                }
            }
            catch (Exception ex)
            {
                LogHelp.WriteOrcaleError(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + ex.Message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()), ex);//add:Wangjh 2017-8-30
                LogHelp.WriteError(ex.Message + strMessage, ex);
                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>接收订单数据失败" + ex.Message + "</document></ReqMsg>";

            }
        }

        #endregion

        #region ERP==>MES订单状态信息集成接口
        //add by longb 2022-11-24
        [WebMethod]
        public string ERP_Send_OrderStatus_Service(string strMessage)
        {
            LogHelp.SetConfig();
            try
            {
                LogHelp.WriteLog(strMessage);
                XmlDocument myxml = XMLParse.getDocument(strMessage);
                XmlNode docnode = XMLParse.getNode(myxml, "/ReqMsg/document");
                Dictionary<string, string> strList = new Dictionary<string, string>();
                strList.Add("MfgOrderName", docnode.SelectSingleNode("AUFNR").InnerText);//生产订单号
                string mfgordername = strList["MfgOrderName"];
                strList.Add("OrderStatus", docnode.SelectSingleNode("ZTECO").InnerText == "1" ? "关闭" : "打开");//是否关闭 1关闭，0打开
                strList.Add("IsPaused", docnode.SelectSingleNode("ZPAUSE").InnerText);//是否暂停 1暂停，0不暂停
                strList.Add("Techconfirm", docnode.SelectSingleNode("ZDLV").InnerText);//是否完全交货
                strList.Add("IsDel", docnode.SelectSingleNode("ZDEL").InnerText);//是否删除 1是 0 否 add by longb 2023-05-09
                if (strList["IsDel"].Equals("1"))//删除的同时将订单关闭 add by longb 2023-05-09
                {
                    strList["OrderStatus"] = "关闭";
                }
                if (erpMethod.GetProductByMfgorder(mfgordername).Rows.Count == 0)
                {
                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + "订单" + mfgordername + "在MES中不存在" + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30
                    LogHelp.WriteLog("订单" + mfgordername + "在MES中不存在:" + strMessage);
                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>true</isSuccess></header><document>订单：" + mfgordername + "在MES中不存在</document></ReqMsg>";
                }
                var result = erpMethod.UpdateMfgOrderStatus(strList);
                if (result)
                {
                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + "订单" + mfgordername + "状态接收成功" + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30
                    LogHelp.WriteLog("订单" + mfgordername + "状态接收成功:" + strMessage);
                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>true</isSuccess></header><document>接收" + mfgordername + "订单状态数据成功</document></ReqMsg>";
                }
                else
                {
                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + "订单" + mfgordername + "状态接收失败" + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30
                    LogHelp.WriteLog("订单" + mfgordername + "状态接收失败:" + strMessage);
                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>接收" + mfgordername + "订单状态数据失败" + "</document></ReqMsg>";
                }
            }
            catch (Exception ex)
            {
                LogHelp.WriteOrcaleError(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + ex.Message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()), ex);//add:Wangjh 2017-8-30
                LogHelp.WriteError(ex.Message + strMessage, ex);
                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>接收订单状态数据失败" + ex.Message + "</document></ReqMsg>";

            }

        }
        #endregion

        #region BPM==>MES出库单信息返回（工序外包流程审批结果接口）
        //add by longb 2022-11-26
        [WebMethod]
        public string BPM_Send_MES_Service(string BUSINESSID, string BUSINESSDATA)
        {
            LogHelp.SetConfig();
            string strMessage = BUSINESSDATA;
            try
            {
                LogHelp.WriteLog("businessID【" + BUSINESSID + "】businessData:" + BUSINESSDATA);
                var JsonDic = JsonConvert.DeserializeObject<Dictionary<string, object>>(strMessage);
                string flowNo = JsonDic["FLOWNO"].ToString();//流程编号
                bool result = false;
                if (BUSINESSID == "3001")//入库 add by zhangrj 2022-12-16
                {
                    result = updateCommissioningDataByInstore(JsonDic);
                }
                else
                {
                    result = updateCommissioningData(JsonDic);
                }
                if (result)
                {
                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + "流程编号" + flowNo + "接收成功" + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));
                    LogHelp.WriteLog("流程编号" + flowNo + strMessage);
                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>true</isSuccess></header><document>" + flowNo + "接收审批结果数据成功</document></ReqMsg>";
                }
                else
                {
                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + "流程编号" + flowNo + "接收失败" + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));
                    LogHelp.WriteLog("流程编号" + flowNo + "接收失败:" + strMessage);
                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>" + flowNo + "接收审批结果数据失败" + "</document></ReqMsg>";
                }
            }
            catch (Exception ex)
            {
                LogHelp.WriteOrcaleError(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + ex.Message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()), ex);
                LogHelp.WriteError(ex.Message + strMessage, ex);
                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>接收审批结果数据失败" + ex.Message + "</document></ReqMsg>";

            }
        }
        public bool updateCommissioningData(Dictionary<string, object> dic)
        {
            bool result = false;
            var arrList = new ArrayList();
            try
            {
                if (dic["AUDITRESULT"].ToString() == "20" || dic["AUDITRESULT"].ToString() == "30")//20：撤销，30：不通过
                {
                    var strSql = string.Format("Update CONTAINERCOMMISSIONING cc SET cc.auditresult='{0}',cc.outdate= NULL,cc.issendbpm=0,cc.outsourcpactno=NULL,cc.lifnr=NULL,cc.lname=NULL where cc.bpmid='{1}'", dic["AUDITRESULT"].ToString(), dic["FLOWNO"].ToString());
                    arrList.Add(strSql);
                }
                else
                {
                    if (dic["AUDITRESULT"].ToString() == "40") //通过
                    {
                        var itemsDt = JsonConvert.DeserializeObject<DataTable>(dic["ITEMS"].ToString());
                        foreach (DataRow row in itemsDt.Rows)
                        {
                            var deSql = @"UPDATE CONTAINERCOMMIDETAIL SET OUTBOUNDROWNUM='{0}' WHERE OUTBOUNDROWNUM is null and isuse=0 and  WORKFLOWSTEPID in (SELECT DISTINCT workflowstepid FROM workflowstep WHERE workflowstepname = '{1}')
                                    AND CONTAINERID=(SELECT DISTINCT CONTAINERID FROM CONTAINERCOMMISSIONING WHERE bpmid='{2}')";
                            arrList.Add(string.Format(deSql, row["AITEM"], row["VORNR_HEAD"] + "-" + row["LTXA1_HEAD"], dic["FLOWNO"].ToString()));
                        }
                    }
                    var strSql = string.Format("Update CONTAINERCOMMISSIONING SET auditresult='{0}',OUTSOURCOUTNO='{1}' where bpmid='{2}'", dic["AUDITRESULT"].ToString(), dic["ACODE"].ToString(), dic["FLOWNO"].ToString());
                    //result = OracleHelper.ExecuteSql(strSql) > 0;
                    arrList.Add(strSql);

                }
                OracleHelper.ExecuteSqlTran(arrList);
                result = true;
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 更新入库外委数据 add by zhangrj 2022-12-16
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        public bool updateCommissioningDataByInstore(Dictionary<string, object> dic)
        {
            bool result = false;
            try
            {
                var strSql = string.Format("update CONTAINERCOMMISSIONING ccm SET ccm.instoreauditresult = '{0}',ccm.instoreauditmsg='{1}' WHERE ccm.instorebpmid = '{2}'", dic["AUDITRESULT"].ToString(), dic["AUDITMSG"].ToString(), dic["FLOWNO"].ToString());
                result = OracleHelper.ExecuteSql(strSql) > 0;
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }

        #endregion

        #region  MES和ERP领料信息集成接口
        [WebMethod]
        public string ERP_Send_Material_Service(string strMessage)
        {
            LogHelp.SetConfig();
            LogHelp.WriteLog("ERP发送发料信息" + strMessage);
            //   strMessage = "<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><sendSysName>APP_SAP</sendSysName><rcvSysName>APP_MES</rcvSysName><extConfig><isReTry>false</isReTry></extConfig></header><document><Item><AFKO-AUFNR>100000000041</AFKO-AUFNR><LJH>S13.21.8357</LJH><AFPO-CHARG>1608001</AFPO-CHARG><CLPH>材料牌号</CLPH><AFKO-GAMNG>1</AFKO-GAMNG><LH>熔炉号1</LH><JXPH>检验编号1</JXPH><KFBG>库房保管1</KFBG><QCJY>器材检验1</QCJY><DLPH>代料牌号1</DLPH><DLGG>代料规格1</DLGG><DLDH>代料单号1</DLDH><PXZYDH>平行作业单号1</PXZYDH><PXZYGX>平行作业工序1</PXZYGX></Item><Item><AFKO-AUFNR>100000000041</AFKO-AUFNR><LJH>S13.21.8357</LJH><AFPO-CHARG>1608002</AFPO-CHARG><CLPH>材料牌号</CLPH><AFKO-GAMNG>1</AFKO-GAMNG><LH>熔炉号1</LH><JXPH>检验编号1</JXPH><KFBG>库房保管1</KFBG><QCJY>器材检验1</QCJY><DLPH>代料牌号1</DLPH><DLGG>代料规格1</DLGG><DLDH>代料单号1</DLDH><PXZYDH>平行作业单号1</PXZYDH><PXZYGX>平行作业工序1</PXZYGX></Item><Item><AFKO-AUFNR>100000000041</AFKO-AUFNR><LJH>S13.21.8357</LJH><AFPO-CHARG>1608003</AFPO-CHARG><CLPH>材料牌号</CLPH><AFKO-GAMNG>1</AFKO-GAMNG><LH>熔炉号3</LH><JXPH>检验编号1</JXPH><KFBG>库房保管3</KFBG><QCJY>器材检验1</QCJY><DLPH>代料牌号1</DLPH><DLGG>代料规格1</DLGG><DLDH>代料单号1</DLDH><PXZYDH>平行作业单号1</PXZYDH><PXZYGX>平行作业工序1</PXZYGX></Item><Item><AFKO-AUFNR>100000000041</AFKO-AUFNR><LJH>S13.21.8357</LJH><AFPO-CHARG>1608004</AFPO-CHARG><CLPH>材料牌号</CLPH><AFKO-GAMNG>1</AFKO-GAMNG><LH>熔炉号4</LH><JXPH>检验编号4</JXPH><KFBG>库房保管4</KFBG><QCJY>器材检验4</QCJY><DLPH>代料牌号4</DLPH><DLGG>代料规格4</DLGG><DLDH>代料单号4</DLDH><PXZYDH>平行作业单号4</PXZYDH><PXZYGX>平行作业工序4</PXZYGX></Item><Item><AFKO-AUFNR>100000000041</AFKO-AUFNR><LJH>S13.21.8357</LJH><AFPO-CHARG>1608005</AFPO-CHARG><CLPH>材料牌号5</CLPH><AFKO-GAMNG>1</AFKO-GAMNG><LH>熔炉号5</LH><JXPH>检验编号5</JXPH><KFBG>库房保管5</KFBG><QCJY>器材检验5</QCJY><DLPH>代料牌号5</DLPH><DLGG>代料规格5</DLGG><DLDH>代料单号5</DLDH><PXZYDH>平行作业单号5</PXZYDH><PXZYGX>平行作业工序5</PXZYGX></Item></document></ReqMsg>";
            ERPSendMESDataMethod erpMethod = new ERPSendMESDataMethod();
            try
            {
                XmlDocument mydoc = XMLParse.getDocument(strMessage);
                XmlNode docnode = XMLParse.getNode(mydoc, "/ReqMsg/document");
                string strMessageInfo = "";
                string strContainers = "";

                #region 暂存数据 转化为Table add:Wangjh 20171129

                DataTable xmlTable = new DataTable();
                xmlTable.Columns.Add("mfgordername");
                xmlTable.Columns.Add("containerName");
                xmlTable.Columns.Add("CLPH");//材料牌号	
                xmlTable.Columns.Add("SXH");//实发数量/顺序号
                xmlTable.Columns.Add("LH");//熔炉号	
                xmlTable.Columns.Add("JXPH");//检验编号
                xmlTable.Columns.Add("KFBG");//库房保管(物资部发料人)
                xmlTable.Columns.Add("QCJY");//器材检验(物资检验人)
                xmlTable.Columns.Add("DLPH");//代料牌号
                xmlTable.Columns.Add("DLGG");//代料规格
                xmlTable.Columns.Add("DLDH");//代料单号
                xmlTable.Columns.Add("PXZYDH");//平行作业单号
                xmlTable.Columns.Add("PXZYGX");//平行作业工序
                xmlTable.Columns.Add("productName");//零件图号
                xmlTable.Columns.Add("ChildContainerName");//批量带子序号的子流水卡，否则则是原流水卡
                xmlTable.Columns.Add("NAME1");
                xmlTable.Columns.Add("GKDB");//顾客代表
                xmlTable.Columns.Add("DLBZ");//代料标准
                //add:Wangjh 20220121
                xmlTable.Columns.Add("BHGSL");//不合格审理单号
                xmlTable.Columns.Add("XLR");//下料人（报工人）
                xmlTable.Columns.Add("XLSJ");//下料时间
                xmlTable.Columns.Add("XLJY");//下料检验
                xmlTable.Columns.Add("JYSJ");//检验时间
                xmlTable.Columns.Add("XLJS");//下料数量
                xmlTable.Columns.Add("HGSL");//合格数量
                xmlTable.Columns.Add("BFSL");//报废数量
                xmlTable.Columns.Add("CCSL");//超差数量
                xmlTable.Columns.Add("FXSL");//返修数量
                xmlTable.Columns.Add("BZ");//备注
                //
                Dictionary<string, string> strLH = new Dictionary<string, string>();
                foreach (XmlNode xn in docnode.ChildNodes)
                {
                    if (xn.Name != "Item")
                    { continue; }
                    DataRow dr = xmlTable.NewRow();
                    dr["mfgordername"] = xn.SelectSingleNode("AFKO-AUFNR").InnerText.Trim();
                    string productName = xn.SelectSingleNode("LJH").InnerText.Trim();
                    DataTable temDt = erpMethod.GetProductByMfgorder(dr["mfgordername"].ToString());
                    if (temDt.Rows.Count > 0)
                        productName = temDt.Rows[0]["ProductName"].ToString();
                    dr["containerName"] = productName + "/" + xn.SelectSingleNode("AFPO-CHARG").InnerText.Trim();
                    dr["CLPH"] = xn.SelectSingleNode("CLPH").InnerText.Trim();//材料牌号	
                    dr["SXH"] = xn.SelectSingleNode("AFKO-GAMNG").InnerText.Trim();//实发数量/顺序号
                    dr["LH"] = xn.SelectSingleNode("LH").InnerText.Trim().Replace(":", "：");//熔炉号
                    dr["JXPH"] = xn.SelectSingleNode("JXPH").InnerText.Trim();//检验编号	
                    //add:Wangjh 20180613 存储熔炉号，可能同一批次多个熔炉号
                    if (strLH.ContainsKey(dr["containerName"].ToString()))
                        strLH[dr["containerName"].ToString()] += "," + string.Format("{0}:{1}:{2}", dr["LH"], dr["SXH"], dr["JXPH"]);
                    else
                        strLH.Add(dr["containerName"].ToString(), string.Format("{0}:{1}:{2}", dr["LH"], dr["SXH"], dr["JXPH"]));
                    //

                    dr["KFBG"] = xn.SelectSingleNode("KFBG").InnerText.Trim();//库房保管(物资部发料人)
                    dr["QCJY"] = xn.SelectSingleNode("QCJY").InnerText.Trim();//器材检验(物资检验人)
                    dr["DLPH"] = xn.SelectSingleNode("DLPH").InnerText.Trim();//代料牌号
                    dr["DLGG"] = xn.SelectSingleNode("DLGG").InnerText.Trim();//代料规格
                    dr["DLDH"] = xn.SelectSingleNode("DLDH").InnerText.Trim();//代料单号
                    if (xn.SelectNodes("DLBZ").Count > 0)
                    {
                        dr["DLBZ"] = xn.SelectSingleNode("DLBZ").InnerText.Trim();//代料标准
                    }

                    dr["PXZYDH"] = xn.SelectSingleNode("PXZYDH").InnerText.Trim();//平行作业单号
                    dr["PXZYGX"] = xn.SelectSingleNode("PXZYGX").InnerText.Trim();//平行作业工序
                    dr["productName"] = productName;//零件图号
                    dr["ChildContainerName"] = dr["containerName"];
                    dr["NAME1"] = xn.SelectSingleNode("NAME1").InnerText.Trim();//供应商
                    if (xn.SelectNodes("GKDB").Count > 0)
                    {
                        dr["GKDB"] = xn.SelectSingleNode("GKDB").InnerText.Trim();//顾客代表                    
                    }
                    if (xn.SelectNodes("BHGSL").Count > 0)//不合格审理单号   
                    {
                        dr["BHGSL"] = xn.SelectSingleNode("BHGSL").InnerText.Trim();
                    }
                    if (xn.SelectNodes("XLR").Count > 0)//下料人（报工人）   
                    {
                        dr["XLR"] = xn.SelectSingleNode("XLR").InnerText.Trim();
                    }
                    if (xn.SelectNodes("XLSJ").Count > 0)//下料时间   
                    {
                        dr["XLSJ"] = xn.SelectSingleNode("XLSJ").InnerText.Trim();
                    }
                    if (xn.SelectNodes("XLJY").Count > 0)//下料检验   
                    {
                        dr["XLJY"] = xn.SelectSingleNode("XLJY").InnerText.Trim();
                    }
                    if (xn.SelectNodes("JYSJ").Count > 0)//检验时间   
                    {
                        dr["JYSJ"] = xn.SelectSingleNode("JYSJ").InnerText.Trim();
                    }
                    if (xn.SelectNodes("XLJS").Count > 0)//下料数量   
                    {
                        dr["XLJS"] = xn.SelectSingleNode("XLJS").InnerText.Trim();
                    }
                    if (xn.SelectNodes("HGSL").Count > 0)//合格数量   
                    {
                        dr["HGSL"] = xn.SelectSingleNode("HGSL").InnerText.Trim();
                    }
                    if (xn.SelectNodes("BFSL").Count > 0)//报废数量   
                    {
                        dr["BFSL"] = xn.SelectSingleNode("BFSL").InnerText.Trim();
                    }
                    if (xn.SelectNodes("CCSL").Count > 0)//超差数量   
                    {
                        dr["CCSL"] = xn.SelectSingleNode("CCSL").InnerText.Trim();
                    }
                    if (xn.SelectNodes("FXSL").Count > 0)//返修数量   
                    {
                        dr["FXSL"] = xn.SelectSingleNode("FXSL").InnerText.Trim();
                    }
                    if (xn.SelectNodes("BZ").Count > 0)//备注   
                    {
                        dr["BZ"] = xn.SelectSingleNode("BZ").InnerText.Trim();
                    }

                    xmlTable.Rows.Add(dr);

                }
                //如果是批量带子序号的增加子序号数据，否则则是原流水卡
                //DataTable tempDt = xmlTable.DefaultView.ToTable(true, "ContainerName", "ChildContainerName");
                //foreach (DataRow dr in tempDt.Rows)
                //{
                //    string containerName = dr["ContainerName"].ToString();
                //    DataTable childDt = erpMethod.QueryChildContainer(containerName);
                //    if (childDt.Rows.Count == 0)
                //    {
                //        continue;
                //    }
                //    DataRow[] drs = xmlTable.Select("ContainerName='" + containerName + "'");
                //    for (int i = 0; i < drs.Length; i++)
                //    {
                //        try
                //        {
                //            if (childDt.Rows[i].IsNull("containername"))
                //            {
                //                continue;
                //            }
                //            drs[i]["ChildContainerName"] = childDt.Rows[i]["containername"];
                //        }
                //        catch (Exception ex)
                //        {
                //            LogHelp.WriteLog(ex.Message);
                //            LogHelp.WriteOrcaleError(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + ex.Message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()), ex);//add:Wangjh 2017-8-30
                //        }
                //    }
                //}
                xmlTable.AcceptChanges();


                #endregion
                //处理数据
                string tempContainerName = "";
                foreach (DataRow dr in xmlTable.Rows)
                {

                    Dictionary<string, string> strList = new Dictionary<string, string>();
                    if (tempContainerName == dr["ChildContainerName"].ToString())//同一批次推了多次,多熔炉号
                        continue;
                    try
                    {
                        strList.Add("containerName", dr["ChildContainerName"].ToString());
                        strList.Add("材料牌号", dr["CLPH"].ToString());
                        if (!string.IsNullOrWhiteSpace(strLH[dr["ChildContainerName"].ToString()]))
                            erpMethod.UpdateBatchcomments(strLH[dr["ChildContainerName"].ToString()], dr["ChildContainerName"].ToString());


                        var sxhs = strLH[dr["ChildContainerName"].ToString()].Split(',');
                        if (sxhs.Length > 1)
                        {
                            double sxh = 0;
                            foreach (var _sxh in sxhs)
                            {
                                sxh += Convert.ToDouble(_sxh.Split(':')[1]);
                            }
                            dr["SXH"] = sxh.ToString();
                        }
                    }
                    catch (Exception ex)
                    {

                    }

                    strList.Add("实发数/顺序号", dr["SXH"].ToString());

                    strList.Add("熔炉号母", dr["LH"].ToString());
                    //strList.Add("熔炉号母", strLH["ChildContainerName"].ToString());
                    strList.Add("检验编号", dr["JXPH"].ToString());
                    strList.Add("库房保管", dr["KFBG"].ToString());
                    strList.Add("器材检验", dr["QCJY"].ToString());
                    strList.Add("代料牌号", dr["DLPH"].ToString());
                    strList.Add("代料规格", dr["DLGG"].ToString());
                    strList.Add("代料单号", dr["DLDH"].ToString());
                    strList.Add("代料标准", dr["DLBZ"].ToString());
                    strList.Add("平行作业单号", dr["PXZYDH"].ToString());
                    strList.Add("平行作业工序", dr["PXZYGX"].ToString());
                    strList.Add("发料时间", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));//add:Wangjh 20181115 增加发料时间属性
                    strList.Add("供应商", dr["NAME1"].ToString());
                    strList.Add("顾客代表", dr["GKDB"].ToString());
                    strList.Add("不合格审理单号", dr["BHGSL"].ToString());//不合格审理单号

                    //报工信息
                    var reportInfo = new Dictionary<string, string>();
                    reportInfo.Add("containerName", dr["containerName"].ToString());//备注
                    reportInfo.Add("XLR", dr["XLR"].ToString());//下料人（报工人）
                    reportInfo.Add("XLSJ", dr["XLSJ"].ToString());//下料时间   
                    reportInfo.Add("XLJY", dr["XLJY"].ToString());//下料检验  
                    reportInfo.Add("JYSJ", dr["JYSJ"].ToString());//检验时间   
                    reportInfo.Add("XLJS", dr["XLJS"].ToString());//下料数量
                    reportInfo.Add("HGSL", dr["HGSL"].ToString());//合格数量
                    reportInfo.Add("BFSL", dr["BFSL"].ToString());//报废数量
                    reportInfo.Add("CCSL", dr["CCSL"].ToString());//超差数量
                    reportInfo.Add("FXSL", dr["FXSL"].ToString());//返修数量
                    reportInfo.Add("BZ", dr["BZ"].ToString());//备注

                    tempContainerName = dr["ChildContainerName"].ToString();
                    string message;

                    //if (dr["ChildContainerName"] == dr["containerName"])
                    //    message = erpMethod.SaveMaterialNew(strList);
                    //else//批量带子序号
                    //    message = erpMethod.SaveChildContainerMaterial(strList);

                    message = erpMethod.SaveMaterialNew(strList);

                    LogHelp.WriteLog(String.Format("message:{0}", message));

                    //下料报工
                    string reportMsg = "";
                    lock (thisLock)
                    {
                        reportMsg = erpMethod.ContainerFisrtAutoCheck(reportInfo);
                    }
                    //如果含有代料单号，需要重新工艺校对
                    if (!string.IsNullOrWhiteSpace(strList["代料单号"]))
                    {
                        erpMethod.ContainerAgainWFConfirm(dr["containerName"].ToString());
                    }

                    if (message.Trim() == "成功")
                    {
                        //对于平行作业暂停的批次，有器材检验的数据后应释放 add:Wangjh 20220713
                        if (!string.IsNullOrWhiteSpace(strList["器材检验"]))
                        {
                            erpMethod.ReleaseContainerByPXZY(dr["containerName"].ToString());
                        }
                        string strContainerID = erpMethod.GetContainerID(dr["ChildContainerName"].ToString());

                        LogHelp.WriteLog("批次" + dr["ChildContainerName"].ToString() + "发料信息接收成功");
                        strMessageInfo = dr["mfgordername"].ToString() + "接收订单发料数据成功," + reportMsg;
                        LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + "批次" + dr["ChildContainerName"].ToString() + "发料信息接收成功," + reportMsg + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30 写入数据库
                        strContainers = String.Format("{0}{1},", strContainers, strContainerID);
                    }
                    else
                    {
                        LogHelp.WriteLog("批次" + dr["ChildContainerName"].ToString() + "接收失败" + message);
                        strMessageInfo = dr["mfgordername"].ToString() + message + reportMsg;
                        LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + "批次" + dr["ChildContainerName"].ToString() + "" + message.Replace("\'", "\"") + reportMsg + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30 写入数据库

                    }

                }
                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>true</isSuccess></header><document><message>" + strMessageInfo + "</message><CID>" + strContainers + "</CID></document></ReqMsg>";
            }
            catch (Exception ex)
            {
                LogHelp.WriteError(ex.Message, ex);
                LogHelp.WriteOrcaleError(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + ex.Message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()), ex);//add:Wangjh 2017-8-30
                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document><message>接收订单发料数据失败" + ex.Message + "</message><CID></CID></document></ReqMsg>";
            }
        }
        #endregion

        #region MES和ERP设备信息集成接口
        [WebMethod]
        public string ERP_Send_Resource_Service(string strMessage)
        {
            log4net.Config.XmlConfigurator.Configure();

            ERPSendMESDataMethod erpMethod = new ERPSendMESDataMethod();
            try
            {
                XmlDocument mydoc = XMLParse.getDocument(strMessage);

                LogHelp.WriteLog("ERP发送信息" + strMessage);
                XmlNode docnode = XMLParse.getNode(mydoc, "/ReqMsg/document");

                string Name = docnode.SelectSingleNode("EQUI-EQUNR").InnerText;//设备编码
                string Description = docnode.SelectSingleNode("EQUI-EQKTX").InnerText;//设备名称
                string ResourceFamily = docnode.SelectSingleNode("EQUI-TYPBZ").InnerText;//型号

                //yuxj20221101 工作中心 从原来的Notes字段改为存到 WorkCenterCode字段，暂将Note字段置空，保留以后使用 
                string Note = ""; //docnode.SelectSingleNode("CRHD-ARBPL").InnerText;
                string WorkCenterCode = "";
                if (docnode.SelectSingleNode("CRHD-ARBPL") != null)
                {
                    WorkCenterCode = docnode.SelectSingleNode("CRHD-ARBPL").InnerText;//生产工作中心
                }
                string Factory = docnode.SelectSingleNode("KTEXT").InnerText;//使用部门名称
                if (string.IsNullOrWhiteSpace(Factory))
                {//add by longb 2023-09-18 
                    LogHelp.WriteLog(Name + "接收失败:使用部门不能为空||" + strMessage);
                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + Name + "接收失败:使用部门不能为空" + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30 写入数据库
                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>" + Name + "接收数据失败:使用部门不能为空</document></ReqMsg>";
                }

                Dictionary<string, string> strList = new Dictionary<string, string>();
                strList.Add("Name", Name);
                strList.Add("Description", Description);
                strList.Add("ResourceFamily", ResourceFamily);
                strList.Add("WorkCenterCode", WorkCenterCode);
                //strList.Add("Notes", Note);
                strList.Add("Factory", Factory);
                //if (docnode.SelectSingleNode("EQUI-TYPBZ").InnerText!=null)
                //{//add:wangjh 2023/1/6
                //    strList.Add("ERPStatus", docnode.SelectSingleNode("EQUI-TYPBZ").InnerText);
                //}

                if (docnode.SelectSingleNode("STTXU") != null)
                { //add:Wangjh 2023/1/6
                    strList.Add("ERPStatus", docnode.SelectSingleNode("STTXU").InnerText);
                }
                string message = erpMethod.SaveResource(strList, false);
                //if (Factory.Contains("机匣"))//add:Wangjh 20170925  分发已取消
                //{
                //    string JXmessage = erpMethod.SaveResource(strList,true );
                //}

                if (message.Trim() == "")
                {
                    LogHelp.WriteLog(Name + "信息接收成功");

                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + Name + "信息接收成功" + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30 写入数据库
                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>true</isSuccess></header><document>" + Name + "接收数据成功</document></ReqMsg>";
                }
                else
                {
                    LogHelp.WriteLog(Name + "接收失败" + message + "||" + strMessage);
                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + Name + "接收失败" + message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30 写入数据库
                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>" + Name + "接收数据失败</document></ReqMsg>";

                }

            }
            catch (Exception ex)
            {
                LogHelp.WriteError("接收失败", ex);
                LogHelp.WriteOrcaleError(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + ex.Message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()), ex);//add:Wangjh 2017-8-30
                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>接收数据失败</document></ReqMsg>";

            }
        }
        #endregion

        #region MES和ERP配送状态传递集成接口
        [WebMethod]
        public string ERP_Send_Distribution_Service(string strMessage)
        {
            log4net.Config.XmlConfigurator.Configure();

            ERPSendMESDataMethod erpMethod = new ERPSendMESDataMethod();
            try
            {
                LogHelp.WriteLog("MES和ERP配送状态传递xml:" + strMessage);
                XmlDocument mydoc = XMLParse.getDocument(strMessage);
                XmlNode docnode = XMLParse.getNode(mydoc, "/ReqMsg/document");
                string Name = docnode.SelectSingleNode("ALCNR").InnerText;//派工单号 UPDATE:Wangjh 20171220 PGD->ALCNR
                string Status = docnode.SelectSingleNode("DPSZA").InnerText;//配送状态 UPDATE:Wangjh 20171220 STATUS->DPSZA
                string Matnr = docnode.SelectSingleNode("MATNR").InnerText;//工装工具编码

                Dictionary<string, string> strList = new Dictionary<string, string>();
                strList.Add("DispatchID", Name);
                strList.Add("Status", Status);
                strList.Add("Type", "arrangement");//UPDATE:Wangjh 20171220 ERPdispatching->arrangement
                strList.Add("ToolNo", Matnr);//add:Wangjh 增加工具编码 20171013


                #region add:Wangjh 2017-10-13 增加更新工具状态代码

                string updateStatusSql = string.Format(@"
                        UPDATE ARRANGEMENTS A SET A.TOOLSTATUS='{0}' WHERE A.ARRANGEMENTSID2='{1}' 
                        and a.toolno='{2}' ", strList["Status"], strList["DispatchID"], strList["ToolNo"]);

                OracleHelper.ExecuteSql(updateStatusSql);
                strList.Add("ArrangementsID", Name);
                #endregion

                string message = erpMethod.SaveDispatchingRecordStatus(strList);
                LogHelp.WriteLog("MES和ERP配送状态传递成功！" + message);
                LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + "MES和ERP配送状态传递成功" + message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30 写入数据库
                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>true</isSuccess></header><document>" + Name + "接收数据成功</document></ReqMsg>";

                //  LogHelp .WriteLog("批次" + containerName + "发料信息接收成功");
                //if (message.Trim() == "")
                //{
                //      LogHelp .WriteLog("MES和ERP配送状态传递成功！"+message);
                //    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>true</isSuccess></header><document>" + Name + "接收数据成功</document></ReqMsg>";
                //}
                //else
                //{
                //      LogHelp .WriteLog("MES和ERP配送状态传递失败！"+message);
                //    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>true</isSuccess></header><document>" + Name + "接收数据失败</document></ReqMsg>";

                //}

                //return erpMethod.CreateXML(message, (message == m_strSuccess) ? true : false);
            }
            catch (Exception ex)
            {
                LogHelp.WriteError("MES和ERP配送状态传递失败", ex);
                LogHelp.WriteOrcaleError(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + "MES和ERP配送状态传递失败 " + ex.Message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()), ex);//add:Wangjh 2017-8-30

                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>接收数据失败</document></ReqMsg>";

            }
        }


        #endregion

        #region MES和DNC程序准备状态传递集成接口
        [WebMethod]
        public string DNC_Send_PrepareStatus_Service(string strMessage)
        {
            log4net.Config.XmlConfigurator.Configure();

            ERPSendMESDataMethod erpMethod = new ERPSendMESDataMethod();
            try
            {
                //                strMessage = @"<?xml version='1.0' encoding='utf-8'?>
                //                    <ReqMsg><header><sendSysName>APP_DNC</sendSysName>
                //                    <rcvSysName>APP_MES</rcvSysName></header>
                //                    <document><![CDATA[<pgd>48001c8000003266</pgd><status>qwe</status>]]></document>
                //                    </ReqMsg>";
                XmlDocument mydoc = XMLParse.getDocument(strMessage);

                XmlNode docnode = XMLParse.getNode(mydoc, "/ReqMsg/document");
                string strXML = docnode.InnerText;//<pgd>20170308125910891</pgd><status>没有找到对应机床编码：CIN-1</status>
                string Name = GetNodeValue(strXML, "pgd");//派工单号
                string Status = GetNodeValue(strXML, "status");// docnode.SelectSingleNode("status").InnerText;//配送状态

                Dictionary<string, string> strList = new Dictionary<string, string>();
                strList.Add("DispatchID", Name);
                strList.Add("Status", Status);
                strList.Add("Type", "DNCdispatching");
                strList.Add("ArrangementsID", Name);
                string message = erpMethod.SaveDispatchingRecordStatus(strList);
                //  LogHelp .WriteLog("批次" + containerName + "发料信息接收成功");
                if (message.Trim() == "")
                {
                    LogHelp.WriteLog(Name + "信息接收成功");
                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + Name + "信息接收成功" + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30 写入数据库

                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>true</isSuccess></header><document>" + Name + "接收数据成功</document></ReqMsg>";
                }
                else
                {
                    LogHelp.WriteLog(Name + "接收失败" + message);
                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + Name + "接收失败" + message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30 写入数据库

                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>" + Name + "接收数据失败</document></ReqMsg>";
                }

                //return erpMethod.CreateXML(message, (message == m_strSuccess) ? true : false);
            }
            catch (Exception ex)
            {
                LogHelp.WriteError("接收失败" + strMessage, ex);
                LogHelp.WriteOrcaleError(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + ex.Message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()), ex);//add:Wangjh 2017-8-30

                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>接收数据失败</document></ReqMsg>";

            }
        }
        #endregion

        private string GetNodeValue(string strSource, string strKey)
        {
            int s = strSource.IndexOf("<" + strKey + ">") + strKey.Length + 2;
            int e = strSource.IndexOf("</" + strKey + ">");
            return strSource.Substring(s, e - s);
        }

        #region MES和ERP集件信息接口
        [WebMethod]
        public string ERP_Send_Component_Service(string strMessage)
        {
            log4net.Config.XmlConfigurator.Configure();

            ERPSendMESDataMethod erpMethod = new ERPSendMESDataMethod();
            try
            {
                if (strMessage != string.Empty)
                {
                    if (strMessage.Substring(0, 1) != "<")
                    {
                        strMessage = strMessage.Substring(1, strMessage.Length - 1);

                    }
                }
                XmlDocument mydoc = XMLParse.getDocument(strMessage);
                XmlNode docnode = XMLParse.getNode(mydoc, "/ReqMsg/document");
                Dictionary<string, string> dict = new Dictionary<string, string>();

                string orderName = docnode.SelectSingleNode("AUFM-AUFNR").InnerText;//生产订单号
                dict.Add("MFGORDERNAME", orderName);
                string productno = docnode.SelectSingleNode("AUFM-MATNR").InnerText;//零部件号
                erpMethod.erpAndTcProductNameHandle(ref productno);
                dict.Add("PRODUCTNAME", productno);
                string qty = docnode.SelectSingleNode("AUFM-MENGE_D").InnerText;//发出数量
                dict.Add("QTY", qty);
                string uom = docnode.SelectSingleNode("AUFM-MEINS").InnerText;//计量单位
                dict.Add("UOM", uom);
                string containerflag = docnode.SelectSingleNode("AUFM-CHARG_D").InnerText;//零件批次号
                dict.Add("PRODUCTBATCHNO", containerflag);
                string nonconforming = docnode.SelectSingleNode("AUFM-BHGSL").InnerText;//是否有不合格品审理 
                //dict.Add("ISNONCONFORMING", orderName);
                // modify by yuxj 20170612
                dict.Add("ISNONCONFORMING", nonconforming);
                string originalProductno = docnode.SelectSingleNode("AUFM-MATNRX").InnerText;//原物料号
                dict.Add("ORIGINALPRODUCTNAME", originalProductno);
                string isOutPlan = docnode.SelectSingleNode("AUFM-JHWFL").InnerText;//是否计划外发料
                dict.Add("ISAUTOPLAN", isOutPlan);
                string Name = string.Format("{0}-{1}-{2}", orderName, containerflag, qty);

                if (string.IsNullOrWhiteSpace(containerflag))
                {   // add by longb 2023-01-13 零件批次号为空，不写入并返回提示信息
                    LogHelp.WriteLog(Name + "接收失败,零件批次号为空：" + strMessage);
                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + Name + "接收失败,零件批次号为空" + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30 写入数据库
                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>" + Name + "接收数据失败,零件批次号为空</document></ReqMsg>";
                }
                string message = erpMethod.InsertCollectERPMaterial(dict);
                #region 机匣测试服务器写入（分发已取消） add:Wangjh 20170925
                //                string queryFactorySql = @" SELECT M.FACTORYID,FA.FACTORYNAME FROM MFGORDER M
                //                                              LEFT JOIN FACTORY FA ON FA.FACTORYID=M.FACTORYID";
                //                queryFactorySql += string.Format (" WHERE M.MFGORDERNAME='{0}'", orderName.Trim());
                //                DataSet factoryDt = OracleHelper.Query(queryFactorySql);
                //                string factory = factoryDt.Tables[0].Rows [0]["FACTORYNAME"].ToString();
                //                if (factory.Contains("机匣"))
                //                {
                //                    dict.Add("IsOtherConn", "true");
                //                    string JXmessage = erpMethod.InsertCollectERPMaterial(dict);
                //                }

                #endregion

                if (message.Trim() == "")
                {
                    LogHelp.WriteLog(Name + "信息接收成功" + strMessage);
                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + Name + "信息接收成功" + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30 写入数据库

                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>true</isSuccess></header><document>" + Name + "接收数据成功</document></ReqMsg>";
                }
                else
                {
                    LogHelp.WriteLog(Name + "接收失败" + strMessage);
                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + Name + "接收失败" + message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30 写入数据库

                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>" + Name + "接收数据失败</document></ReqMsg>";

                }

            }
            catch (Exception ex)
            {
                LogHelp.WriteError("接收失败" + strMessage, ex);
                LogHelp.WriteOrcaleError(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + ex.Message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()), ex);//add:Wangjh 2017-8-30

                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>接收数据失败" + ex.Message + "</document></ReqMsg>";

            }
        }
        #endregion

        #region MES和ERP不合格品审理反馈信息接口
        [WebMethod]
        /// <summary>
        /// add by yuxj 20170613
        /// </summary>
        /// <param name="strMessage"></param>
        /// <returns></returns>
        public string ERP_Send_Nonconforming_Service(string strMessage)
        {
            log4net.Config.XmlConfigurator.Configure();

            ERPSendMESDataMethod erpMethod = new ERPSendMESDataMethod();
            try
            {
                XmlDocument mydoc = XMLParse.getDocument(strMessage);
                Dictionary<string, string> dict = new Dictionary<string, string>();
                XmlNode docnode = XMLParse.getNode(mydoc, "/ReqMsg/document");

                string QMNUM = string.Empty;
                string ZBHGDH = string.Empty;
                XmlNode childNode = docnode.SelectSingleNode("ZQMMES-QMNUM");//通知单编号
                dict.Add("QMNUM", childNode == null ? "" : childNode.InnerText);
                childNode = docnode.SelectSingleNode("ZQMMES-MATNR");//物料号
                dict.Add("MATNR", childNode == null ? "" : childNode.InnerText);
                childNode = docnode.SelectSingleNode("RECORDID");//RECORDID
                dict.Add("RECORDID", childNode == null ? "" : childNode.InnerText);
                childNode = docnode.SelectSingleNode("ZQMMES-FERTAUFNR");//生产订单号
                dict.Add("FERTAUFNR", childNode == null ? "" : childNode.InnerText);
                childNode = docnode.SelectSingleNode("ZQMMES-ZMESGX");//MES工序
                dict.Add("ZMESGX", childNode == null ? "" : childNode.InnerText);
                childNode = docnode.SelectSingleNode("ZQMMES-UVORN");//子工序
                dict.Add("UVORN", childNode == null ? "" : childNode.InnerText);
                childNode = docnode.SelectSingleNode("ZQMMES-ZBHGDH");//不合格品审理单号
                dict.Add("ZBHGDH", childNode == null ? "" : childNode.InnerText);
                childNode = docnode.SelectSingleNode("ZQMMES-ZLPH2");//炉批号
                dict.Add("ZLPH2", childNode == null ? "" : childNode.InnerText);
                childNode = docnode.SelectSingleNode("ZQMMES-ZPCH2");//	机加批次号
                dict.Add("ZPCH2", childNode == null ? "" : childNode.InnerText);
                childNode = docnode.SelectSingleNode("ZQMMES-ZGD2");//	工段
                dict.Add("ZGD2", childNode == null ? "" : childNode.InnerText);
                childNode = docnode.SelectSingleNode("ZQMMES-ZSLJL");//	审理结论
                dict.Add("ZSLJL", childNode == null ? "" : childNode.InnerText);
                childNode = docnode.SelectSingleNode("ZQMMES-ZBZ2");//	备注
                dict.Add("ZBZ2", childNode == null ? "" : childNode.InnerText);
                childNode = docnode.SelectSingleNode("ZQMMES-ZYWLPC2");//	原材料批次号 
                dict.Add("ZYWLPC2", childNode == null ? "" : childNode.InnerText);
                childNode = docnode.SelectSingleNode("ZQMMES-ZJYBH");//	检验编号
                dict.Add("ZJYBH", childNode == null ? "" : childNode.InnerText);
                childNode = docnode.SelectSingleNode("ZQMMES-ZSFGL");//	措施是否归零
                dict.Add("ZSFGL", childNode == null ? "" : childNode.InnerText);
                string Name = string.Format("{0}-{1}", QMNUM, ZBHGDH);
                string message = erpMethod.UpdateUnqualifiedData(dict);
                #region 机匣测试服务器写入（分发已取消） add:Wangjh 20170925
                //                string ID = docnode.SelectSingleNode("RECORDID").InnerText;
                //                string mfgOrderNameSql = string.Format("  select cnon.fertaufnr from containernonconforminginfo cnon where cnon.containernonconforminginfoid='{0}'", ID);
                //                 DataSet mfgDt ;
                //                 DataSet tempDt=OracleHelper.Query(mfgOrderNameSql);
                //                 if (tempDt.Tables[0].Rows.Count == 0)
                //                 {
                //                     mfgDt = OracleHelper.Query(mfgOrderNameSql, true);
                //                 }
                //                 else {
                //                     mfgDt = tempDt;
                //                 }

                //                 string mfgOrderName = mfgDt.Tables[0].Rows[0]["fertaufnr"].ToString ();
                //                string queryFactorySql = @" SELECT M.FACTORYID,FA.FACTORYNAME FROM MFGORDER M
                //                                              LEFT JOIN FACTORY FA ON FA.FACTORYID=M.FACTORYID";
                //                queryFactorySql += string.Format(" WHERE M.MFGORDERNAME='{0}'", mfgOrderName.Trim());
                //                DataSet factoryDt = OracleHelper.Query(queryFactorySql);
                //                string factory = factoryDt.Tables[0].Rows[0]["FACTORYNAME"].ToString();
                //                if (factory.Contains("机匣"))
                //                {
                //                    dict.Add("IsOtherConn", "true");
                //                     message = erpMethod.UpdateUnqualifiedData(dict);
                //                }
                //                else //不合格审理只存在一边又所以做判断
                //                {

                //                     message = erpMethod.UpdateUnqualifiedData(dict);
                //                }
                #endregion


                if (message.Trim() == "")
                {
                    LogHelp.WriteLog(Name + "信息接收成功" + "-" + strMessage);
                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + Name + "信息接收成功" + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30 写入数据库

                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>true</isSuccess></header><document>" + Name + "接收数据成功</document></ReqMsg>";
                }
                else
                {
                    LogHelp.WriteLog(Name + "接收失败" + message + "-" + strMessage);
                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + Name + "接收失败" + message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30 写入数据库

                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>" + Name + "接收数据失败</document></ReqMsg>";

                }
            }
            catch (Exception ex)
            {
                LogHelp.WriteError("接收失败" + "-" + strMessage, ex);
                LogHelp.WriteOrcaleError(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + ex.Message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()), ex);//add:Wangjh 2017-8-30

                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>接收数据失败</document></ReqMsg>";

            }
        }
        #endregion

        #region MES和TDM试车任务信息接口
        [WebMethod]
        /// <summary>
        /// add by yuxj 20170613
        /// </summary>
        /// <param name="strMessage"></param>
        /// <returns></returns>
        public string TDM_Send_TestTask_Service(string strMessage)
        {
            log4net.Config.XmlConfigurator.Configure();
            TDMSendMESDataMethod erpMethod = new TDMSendMESDataMethod();
            //            strMessage = @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><sendSysName>APP_SAP</sendSysName><rcvSysName>APP_MES</rcvSysName>
            //<extConfig><isReTry>false</isReTry></extConfig></header>
            //<document><![CDATA[<ScTask><STATE>3</STATE><MESID>c66d464a-a9c4-48f6-86a7-707aecb40bd3</MESID><CONCLUSION>合格</CONCLUSION><WORKTIME>100</WORKTIME><STATETIME>10</STATETIME></ScTask>]]>
            //</document></ReqMsg>";

            try
            {
                XmlDocument mydoc = XMLParse.getDocument(strMessage);
                Dictionary<string, string> dict = new Dictionary<string, string>();
                XmlNode docnode = XMLParse.getNode(mydoc, "/ReqMsg/document");
                mydoc.LoadXml(docnode.InnerText);
                //XmlElement  xx=  XMLParse.getElement (mydoc, "/Item");
                //XmlNode xxn = xx.SelectSingleNode("AFKO-AUFNR");

                XmlElement Element = XMLParse.getElement(mydoc, "/ScTask");

                #region 试车任务推送信息 add YangJiang 20180703
                XmlNode childNode = Element.SelectSingleNode("MESID");//任务ID
                dict.Add("MESID", childNode == null ? "" : childNode.InnerText);
                childNode = Element.SelectSingleNode("STATE");//状态
                dict.Add("STATE", childNode == null ? "" : childNode.InnerText);
                childNode = Element.SelectSingleNode("CONCLUSION");//返回结果
                dict.Add("CONCLUSION", childNode == null ? "" : childNode.InnerText);
                childNode = Element.SelectSingleNode("WORKTIME");//工作时间
                dict.Add("WORKTIME", childNode == null ? "" : childNode.InnerText);
                childNode = Element.SelectSingleNode("STATETIME");//状态时间
                dict.Add("STATETIME", childNode == null ? "" : childNode.InnerText);
                string message = tdmMethod.UpdateTestTaskData(dict);
                string Name = dict["MESID"];
                #endregion


                if (message.Trim().Contains("更新记录条数"))
                {
                    LogHelp.WriteLog(Name + "信息接收成功" + "-" + strMessage);
                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + Name + "信息接收成功" + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30 写入数据库

                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>true</isSuccess></header><document>" + Name + "接收数据成功</document></ReqMsg>";
                }
                else
                {
                    LogHelp.WriteLog(Name + "接收失败" + message + "-" + strMessage);
                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + Name + "接收失败" + message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30 写入数据库

                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>" + Name + "接收数据失败</document></ReqMsg>";

                }
            }
            catch (Exception ex)
            {
                LogHelp.WriteError("接收失败" + "-" + strMessage, ex);
                LogHelp.WriteOrcaleError(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + ex.Message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()), ex);//add:Wangjh 2017-8-30

                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>接收数据失败</document></ReqMsg>";

            }
        }
        #endregion

        #region MES和TDM部件试验任务信息接口
        [WebMethod]
        /// <summary>
        /// add by yuxj 20170613
        /// </summary>
        /// <param name="strMessage"></param>
        /// <returns></returns>
        public string TDM_Send_PartTask_Service(string strMessage)
        {
            log4net.Config.XmlConfigurator.Configure();

            try
            {
                XmlDocument mydoc = XMLParse.getDocument(strMessage);
                Dictionary<string, string> dict = new Dictionary<string, string>();
                XmlNode docnode = XMLParse.getNode(mydoc, "/ReqMsg/document");

                mydoc.LoadXml(docnode.InnerText);
                XmlElement Element = XMLParse.getElement(mydoc, "/PartTask");

                #region 部件试验任务推送信息 add YangJiang 20180703
                XmlNode childNode = Element.SelectSingleNode("MESID");//任务ID
                dict.Add("MESID", childNode == null ? "" : childNode.InnerText);
                childNode = Element.SelectSingleNode("ISQUALIFIED");//是否合格
                dict.Add("ISQUALIFIED", childNode == null ? "" : childNode.InnerText);
                string message = tdmMethod.UpdatePartTaskData(dict);
                string Name = dict["MESID"];
                #endregion


                if (message.Trim().Contains("更新记录条数"))
                {
                    LogHelp.WriteLog(Name + "信息接收成功" + "-" + strMessage);
                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + Name + "信息接收成功" + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30 写入数据库

                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>true</isSuccess></header><document>" + Name + "接收数据成功</document></ReqMsg>";
                }
                else
                {
                    LogHelp.WriteLog(Name + "接收失败" + message + "-" + strMessage);
                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + Name + "接收失败" + message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30 写入数据库

                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>" + Name + "接收数据失败</document></ReqMsg>";

                }
            }
            catch (Exception ex)
            {
                LogHelp.WriteError("接收失败" + "-" + strMessage, ex);
                LogHelp.WriteOrcaleError(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + ex.Message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()), ex);//add:Wangjh 2017-8-30

                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>接收数据失败</document></ReqMsg>";

            }
        }
        #endregion

        #region 外包系统给mes外包序的报工检验信息 add:Wangjh

        [WebMethod]
        public string SCM_Send_WorkingReport_Service(string strMessage)
        {
            LogHelp.SetConfig();
            var _strMsg = strMessage.Replace(" ", "").Replace("\'", "\"").Replace("\r", "").Replace("\n", "");
            try
            {
                XmlDocument mydoc = XMLParse.getDocument(strMessage);
                XmlNode docnode = XMLParse.getNode(mydoc, "/ReqMsg/document");
                Dictionary<string, object> dict = new Dictionary<string, object>();

                dict.Add("ProductName", docnode.SelectSingleNode("productName").InnerText);
                dict.Add("ContainerNo", docnode.SelectSingleNode("containerNo").InnerText);
                dict.Add("ContainerName", docnode.SelectSingleNode("productName").InnerText + "/" + docnode.SelectSingleNode("containerNo").InnerText);
                dict.Add("WorkflowStepName", docnode.SelectSingleNode("specNo").InnerText + "-" + docnode.SelectSingleNode("specDesc").InnerText);
                if (string.IsNullOrWhiteSpace(docnode.SelectSingleNode("sonSpecNo").InnerText) || string.IsNullOrWhiteSpace(docnode.SelectSingleNode("sonSpecDesc").InnerText))
                {
                    dict.Add("SonWorkflowStepName", "");
                }
                else
                {
                    dict.Add("SonWorkflowStepName", docnode.SelectSingleNode("sonSpecNo").InnerText + "-" + docnode.SelectSingleNode("sonSpecDesc").InnerText);
                }
                dict.Add("PassQty", string.IsNullOrWhiteSpace(docnode.SelectSingleNode("passQty").InnerText) ? "0" : docnode.SelectSingleNode("passQty").InnerText);
                dict.Add("DefectQty", string.IsNullOrWhiteSpace(docnode.SelectSingleNode("defectQty").InnerText) ? "0" : docnode.SelectSingleNode("defectQty").InnerText);
                dict.Add("ReworkQty", string.IsNullOrWhiteSpace(docnode.SelectSingleNode("reworkQty").InnerText) ? "0" : docnode.SelectSingleNode("reworkQty").InnerText);
                dict.Add("ReportQty", string.IsNullOrWhiteSpace(docnode.SelectSingleNode("reportQty").InnerText) ? "0" : docnode.SelectSingleNode("reportQty").InnerText);
                dict.Add("LossQty", string.IsNullOrWhiteSpace(docnode.SelectSingleNode("lossQty").InnerText) ? "0" : docnode.SelectSingleNode("lossQty").InnerText);
                dict.Add("ReportDate", docnode.SelectSingleNode("reportDate").InnerText);
                dict.Add("CheckDate", docnode.SelectSingleNode("checkDate").InnerText);
                dict.Add("LNAMEJHRNAME", docnode.SelectSingleNode("lnamejhrname").InnerText);
                dict.Add("LNAMEJHRPHONE", docnode.SelectSingleNode("lnamejhrphone").InnerText);
                dict.Add("FEVORSHR", docnode.SelectSingleNode("fevorshr").InnerText);
                dict.Add("FHDATE", docnode.SelectSingleNode("fhdate").InnerText);
                dict.Add("ZJFSL", docnode.SelectSingleNode("zjfsl").InnerText);
                dict.Add("LossResonCode", docnode.SelectSingleNode("lossResonCode").InnerText == "null" ? "" : docnode.SelectSingleNode("lossResonCode").InnerText);
                dict.Add("LossResonDesc", docnode.SelectSingleNode("lossResonDesc").InnerText == "null" ? "" : docnode.SelectSingleNode("lossResonDesc").InnerText);
                //
                dict.Add("OutBoundRowNum", docnode.SelectSingleNode("outboundrownum") == null ? "" : docnode.SelectSingleNode("outboundrownum").InnerText);
                dict.Add("OutSourcOutNo", docnode.SelectSingleNode("outsourcoutno").InnerText);

                var childDt = new DataTable();
                childDt.Columns.AddRange(new DataColumn[]{
                    new DataColumn("childContainerNo"),new DataColumn("LossQty"), new DataColumn("LossResonCode"),new DataColumn("LossResonDesc")
                });
                var childItems = docnode.SelectSingleNode("childItems");
                if (childItems.ChildNodes.Count > 0)
                {
                    foreach (XmlNode childItem in childItems.ChildNodes)
                    {
                        var childRow = childDt.NewRow();

                        childRow["childContainerNo"] = childItem.SelectSingleNode("childContainerNo").InnerText;
                        childRow["lossQty"] = childItem.SelectSingleNode("lossQty").InnerText;
                        childRow["lossResonCode"] = childItem.SelectSingleNode("lossResonCode").InnerText;
                        childRow["lossResonDesc"] = childItem.SelectSingleNode("lossResonDesc").InnerText;

                        if (string.IsNullOrWhiteSpace(childRow["lossQty"].ToString()))
                        {
                            childRow["lossQty"] = "0";
                        }

                        childDt.Rows.Add(childRow);
                    }
                }
                childDt.AcceptChanges();

                dict.Add("ChildItems", childDt);//子序号信息

                var re = erpMethod.ContainerCommisonReportAndCheck(dict);

                if (re.Result)//成功，批次需要移动
                {
                    string strMsg = "";

                    foreach (DataRow con in re.DBTable.Rows)
                    {
                        if (con["IsMove"].ToString() == "1")
                        {
                            erpMethod.ContainerMoveStd(con["containerName"].ToString(), "", "", ref strMsg);
                        }
                    }

                    LogHelp.WriteLog(dict["ContainerName"].ToString() + "外包报工接口接收成功" + strMessage);
                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + dict["ContainerName"].ToString() + "外包报工接口接收成功" + "@^" + (_strMsg.Length > 4000 ? "xml太长" : _strMsg) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30 写入数据库

                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>true</isSuccess></header><document>" + dict["ContainerName"].ToString() + "接收数据成功</document></ReqMsg>";

                }
                else
                {
                    LogHelp.WriteLog(dict["ContainerName"].ToString() + "外包报工接口接收失败" + strMessage);
                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + dict["ContainerName"].ToString() + "接收失败" + re.Message.Replace("\'", "\"") + "@^" + (_strMsg.Length > 4000 ? "xml太长" : _strMsg) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30 写入数据库

                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>" + dict["ContainerName"].ToString() + "接收数据失败</document></ReqMsg>";

                }

            }
            catch (Exception ex)
            {
                LogHelp.WriteError("外包报工接口接收失败" + strMessage, ex);
                LogHelp.WriteOrcaleError(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + ex.Message.Replace("\'", "\"") + "@^" + (_strMsg.Length > 4000 ? "xml太长" : _strMsg) + "@^" + Convert.ToString(Guid.NewGuid()), ex);//add:Wangjh 2017-8-30

                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>接收数据失败" + ex.Message + "</document></ReqMsg>";

            }
        }
        #endregion

        #region MES和作动筒信息接口
        [WebMethod]
        /// <summary>
        /// add by YangJiang 20180709
        /// </summary>
        /// <param name="strMessage"></param>
        /// <returns></returns>
        public string ZDSC_Send_WorkReport_Service(string strMessage)
        {
            log4net.Config.XmlConfigurator.Configure();
            try
            {
                XmlDocument mydoc = XMLParse.getDocument(strMessage);
                Dictionary<string, string> dict = new Dictionary<string, string>();
                XmlNode docnode = XMLParse.getNode(mydoc, "/ReqMsg/document");

                mydoc.LoadXml(docnode.InnerText);
                XmlElement Element = XMLParse.getElement(mydoc, "/PartTask");

                #region 部件试验任务推送信息 add YangJiang 20180703
                XmlNode childNode = Element.SelectSingleNode("MESID");//任务ID
                dict.Add("MESID", childNode == null ? "" : childNode.InnerText);
                childNode = Element.SelectSingleNode("ISQUALIFIED");//是否合格
                dict.Add("ISQUALIFIED", childNode == null ? "" : childNode.InnerText);
                string message = tdmMethod.UpdatePartTaskData(dict);
                string Name = dict["MESID"];
                #endregion



                if (message.Trim().Contains("更新记录条数"))
                {
                    LogHelp.WriteLog(Name + "信息接收成功" + "-" + strMessage);
                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + Name + "信息接收成功" + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30 写入数据库

                    return @"<?xml version='1.0' encoding='utf-8'?><RespMsg><header><SysName>APP_MES</SysName><isSuccess>true</isSuccess></header><document>" + Name + "接收数据成功</document></RespMsg>";
                }
                else
                {
                    LogHelp.WriteLog(Name + "接收失败" + message + "-" + strMessage);
                    LogHelp.WriteOrcale(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + Name + "接收失败" + message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30 写入数据库

                    return @"<?xml version='1.0' encoding='utf-8'?><RespMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>" + Name + "接收数据失败</document></RespMsg>";

                }
            }
            catch (Exception ex)
            {
                LogHelp.WriteError("接收失败" + "-" + strMessage, ex);
                LogHelp.WriteOrcaleError(System.Reflection.MethodBase.GetCurrentMethod().Name + "@^" + ex.Message.Replace("\'", "\"") + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()), ex);//add:Wangjh 2017-8-30

                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>接收数据失败</document></ReqMsg>";

            }
        }
        #endregion

        #region Yuxj PDM获取MES实物信息-装机产品 接口
        [WebMethod]
        public string PDM_GetMESIssueMaterial_Service(string strXML)
        {
            //<?xml version="1.0" encoding="utf-8"?><LIST><ae8_drawingNo>C6EPartPhyPart</ae8_drawingNo></LIST>     
            try
            {
                log4net.Config.XmlConfigurator.Configure();
                XmlDocument mydoc = XMLParse.getDocument(strXML);
                XmlNode docnode = XMLParse.getNode(mydoc, "/LIST");
                //零件图号
                if (docnode.SelectSingleNode("ae8_drawingNo") == null)
                {
                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>输入参数【ae8_drawingNo】不存在!</document></ReqMsg>";
                }
                string IssueMaterial = docnode.SelectSingleNode("ae8_drawingNo").InnerText;
                DataTable dtIssue = MESActualMaterial.GetMESIssueMaterial(IssueMaterial);
                StringBuilder sb = new StringBuilder();
                foreach (DataRow dr in dtIssue.Rows)
                {
                    sb.Append("<LIST>");
                    foreach (DataColumn col in dtIssue.Columns)
                    {
                        sb.AppendFormat("<{0}>{1}</{2}>", col.ColumnName, dr[col].ToString(), col.ColumnName);
                    }
                    sb.Append("</LIST>");
                }
                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>true</isSuccess></header><document>" + sb.ToString() + "</document></ReqMsg>";
            }
            catch (Exception ex)
            {
                LogHelp.WriteError("接收失败" + strXML, ex);
                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>" + "请求失败！" + ex.Message + "</document></ReqMsg>";
            }
        }
        #endregion

        #region Zhunan PDM获取MES在制品信息接口
        [WebMethod]
        public string PDM_GetMESProductWipInfo_Service(string strXML)
        {
            log4net.Config.XmlConfigurator.Configure();
            TCGetMESActualMaterial pdmMethod = new TCGetMESActualMaterial();
            try
            {
                StringBuilder sb = new StringBuilder();
                XmlDocument mydoc = XMLParse.getDocument(strXML);
                XmlNode docnode = XMLParse.getNode(mydoc, "document");
                //零件图号
                if (docnode.SelectSingleNode("ae8_drawingNo") == null)
                {
                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>输入参数【ae8_drawingNo】不存在!</document></ReqMsg>";
                }
                string productname = docnode.SelectSingleNode("ae8_drawingNo").InnerText;
                string ly2process_no = docnode.SelectSingleNode("ly2process_no") == null ? "" : docnode.SelectSingleNode("ly2process_no").InnerText;

                Dictionary<string, string> para = new Dictionary<string, string>();
                para.Add("productname", productname);
                para.Add("process_no", ly2process_no);
                DataTable dt = pdmMethod.GetProductWipInfo(para);

                if (dt.Rows.Count == 0)
                {
                    return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>件号不存在!</document></ReqMsg>";
                }

                foreach (DataRow dr in dt.Rows)
                {
                    sb.Append("<LIST>");
                    foreach (DataColumn col in dt.Columns)
                    {
                        sb.AppendFormat("<{0}>{1}</{2}>", col.ColumnName, dr[col].ToString(), col.ColumnName);
                    }
                    sb.Append("</LIST>");
                }
                string res_xml = @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>true</isSuccess></header><document>" + sb.ToString() + "</document></ReqMsg>";
                return res_xml;
            }
            catch (Exception ex)
            {
                LogHelp.WriteError("接收失败" + strXML, ex);
                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES</SysName><isSuccess>false</isSuccess></header><document>" + "请求失败！" + ex.Message + "</document></ReqMsg>";
            }
            finally
            {
                LogHelp.WriteLog("PDM获取MES在制品信息接口接收xml:" + strXML);
            }
        }
        #endregion

        #region 设计更改单--批次暂停接口 add by longb 2023-04-03
        public string PDM_DesignChange_Service(XmlNode mesDoc)
        {
            try
            {
                bool result = false;
                string Message = string.Empty;
                XmlNode meops = mesDoc.SelectSingleNode("Root/Change");
                var ECNNo = meops.SelectSingleNode("ECNNo").InnerText;//设计更改单号
                var decisionToProduct = meops.SelectSingleNode("decisionToProduct").InnerText;//对产品的决定
                var changeReason = meops.SelectSingleNode("changeReason").InnerText;//更改原因
                XmlNode productNode = mesDoc.SelectSingleNode("Root/product/item");
                var productName = productNode.SelectSingleNode("ae8_drawingNo").InnerText;
                var productRev = productNode.SelectSingleNode("item_revision_id").InnerText;
                //if (!decisionToProduct.Equals("无影响"))
                //{
                string strSql = @"select ut.attributevalue,cci.containerid,cci.containername,cci.productid,cci.productname,cci.qty from containercurrentinfo cci 
                        LEFT JOIN userattribute ut ON ut.userattributename='分厂代码' AND ut.parentid=cci.originalfactoryid
                        WHERE cci.isinstore=0 AND NVL(CCI.ishold,0)=0 AND cci.containerstatus <>2";

                if (!string.IsNullOrWhiteSpace(productName))
                {
                    strSql += string.Format(" and cci.productName='{0}' and cci.productrevision!='{1}' ", productName, productRev);
                }
                DataTable conDt = OracleHelper.Query(strSql).Tables[0];
                //暂停所查出的批次
                ArrayList sqls = new ArrayList();
                string sql = "update containercurrentinfo set ishold=1 where containerid='{0}'";
                string sql2 = @"INSERT INTO OperContainerRecord(containerid,containername,productid,productname,operatorid,operreason,qty,createdate,opertype)
                                VALUES('{0}','{1}','{2}','{3}','{4}','{5}',{6},SYSDATE,'2')";
                foreach (DataRow dr in conDt.Rows)
                {
                    sqls.Add(string.Format(sql, dr["containerid"].ToString()));
                    sqls.Add(string.Format(sql2, dr["containerid"].ToString(), dr["containername"].ToString(), dr["productid"].ToString(), dr["productname"].ToString(), "", "产品工艺变更暂停", dr["qty"].ToString()));
                }
                if (sqls.Count > 0)
                {
                    result = OracleHelper.ExecuteSqlTran(sqls, ref Message);
                    if (result) { Message = "设计更改单接收成功,批次暂停成功"; }
                }
                else
                {
                    Message = "根据设计更改单件号信息，查询不到需要暂停的批次信息";
                }
                //}
                return @"<?xml version='1.0' encoding='utf-8'?><RespMsg><header><sysName>APP_MES</sysName><isSuccess>" + result + "</isSuccess><message></message></header><document><![CDATA[<TETTYP><RTYPE>" + result + "</RTYPE><RTMSG>" + Message + "</RTMSG></TETTYP>]]></document></RespMsg>";
            }
            catch (Exception ex)
            {
                return @"<?xml version='1.0' encoding='utf-8'?><RespMsg><header><sysName>APP_MES</sysName><isSuccess>false</isSuccess><message></message></header><document><![CDATA[<TETTYP><RTYPE>false</RTYPE><RTMSG>" + "设计更改单接收失败：" + ex.Message + "</RTMSG></TETTYP>]]></document></RespMsg>";
            }
        }
        #endregion

        #region "数控程序 add by longb 2025-01-14"
        [WebMethod]
        public string UFC_Get_TCToMES_SKCX_Service(string strMessage, Byte[] fileinstance)
        {
            //Byte[] fileinstance=new byte[0];
            LogHelp.SetConfig();
            LogHelp.WriteLog("数控程序接收到的：strMessage " + strMessage);
            var DocPath = ConfigurationManager.AppSettings["NCFilesPath"];

            XmlDocument myxml = new XmlDocument();
            myxml.LoadXml(strMessage);
            string strFileName = "";
            string strProcessName = "";
            string strProcessRev = "";
            string strMeopno = "";//工序号

            XmlNode docnode = XMLParse.getNode(myxml, "/ReqMsg/document");
            strFileName = docnode.SelectSingleNode("document").InnerText;
            strProcessName = docnode.SelectSingleNode("process").InnerText;
            if (docnode.SelectSingleNode("processRev") != null)
            {
                strProcessRev = docnode.SelectSingleNode("processRev").InnerText;
                strMeopno = docnode.SelectSingleNode("meopno") == null ? "" : docnode.SelectSingleNode("meopno").InnerText;
            }
            //推送的如果是附件，则另存
            LogHelp.WriteOrcale("PDMTOMES_NC" + "@^" + "接收到附件" + strFileName + "@^" + "" + "@^" + Convert.ToString(Guid.NewGuid()));
            DocPath += @"\" + strProcessName + "-" + strProcessRev + "-" + strMeopno;
            LogHelp.WriteLog("数控程序接收附件：" + strFileName + "文件大小：" + fileinstance.Length.ToString().Trim());
            if (!Directory.Exists(DocPath))
            {
                Directory.CreateDirectory(DocPath);
            }
            DocPath += @"\" + strFileName;
            FileStream fs = null;
            try
            {
                if (File.Exists(DocPath)) //create:Wangjh 2017-6-26 增加是否为空判断
                {
                    var minutes = 0;
                    try
                    {
                        minutes = (DateTime.Now - File.GetLastWriteTime(DocPath)).Minutes;
                    }
                    catch (Exception ex) { }
                    if (minutes > 5)
                    {
                        File.Delete(DocPath);
                        fs = new FileStream(DocPath, FileMode.OpenOrCreate);
                    }
                    else
                    {
                        fs = new FileStream(DocPath, FileMode.Append);
                    }
                }
                else
                {
                    fs = new FileStream(DocPath, FileMode.OpenOrCreate);
                }

                byte[] Buffer = fileinstance;
                fs.Write(Buffer, 0, Buffer.Length);
                fs.Flush();
            }
            catch (Exception ex)
            {
                LogHelp.WriteLog("接收附件【" + strFileName + "】失败");

                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES_SKCX</SysName><success>0</success><data><![CDATA[接收附件【" + strFileName + "】失败:" + ex.Message + "]]></data></header></ReqMsg>";
            }
            finally
            {
                fs.Close();
            }
            //如果是.xml文件，读取处理写入数据库
            if (strFileName.Contains(".xml"))
            {
                DealNcData(DocPath);
            }
            return "<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES_SKCX</SysName><success>1</success><data><![CDATA[接收附件【" + strFileName + "】成功]]></data></header></ReqMsg>";
        }
        [WebMethod]
        public void DealNcData(string xmlPath)
        {
            try
            {
                var arrList = new ArrayList();
                var insertNC = @"insert into ncprogram(id,nc_no,nc_name,factoryid,process_no,process_rev,specname,specno,productname,productrevision,productdesc,drawingno,material_mark,control_type,isthree,istypical)
                                    values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}')";
                var insertNCD = @"insert into ncprogramdetaile(id,parentid,equip_code,equip_xh,filename,filepath)
                                    values(sys_guid(),'{0}','{1}','{2}','{3}','{4}')";
                var insertDoC = @"INSERT INTO OBJECTDOCINFO(OBJECTDOCINFOID,PARENTID,FILENAME,FILEPATH)
		                            values(sys_guid(),'{0}','{1}','{2}')";
                var selectNC = @"select * from ncprogram nc where nc.nc_no ='{0}' and nc.process_no ='{1}' and nc.process_rev ='{2}'";
                var selectDoc = @"select * from OBJECTDOCINFO o where o.PARENTID ='{0}' and o.FILENAME ='{1}' and o.FILEPATH ='{2}'";
                var selectNCD = @"select * from ncprogramdetaile ncd where ncd.parentid='{0}' and ncd.equip_code='{1}'";
                var selectNCD2 = @"select * from ncprogramdetaile ncd where ncd.parentid='{0}' and ncd.filename='{1}' and ncd.filepath='{2}'";

                var uuid = Guid.NewGuid().ToString();

                XmlDocument myxml = new XmlDocument();
                myxml.Load(xmlPath);
                XmlNode docnode = XMLParse.getNode(myxml, "/Root/LY2MENC");
                var ly2nc_no = docnode.SelectSingleNode("ly2nc_no").InnerText;//数控程序编号
                var object_name = docnode.SelectSingleNode("object_name").InnerText;//数控程序名称
                var ly2plant = docnode.SelectSingleNode("ly2plant").InnerText;//单位(分厂)
                var ly2process_no = docnode.SelectSingleNode("ly2process_no").InnerText;//工艺规程编号
                var ly2process_rev = docnode.SelectSingleNode("ly2process_revID").InnerText;//工艺规程版本
                var meopname = docnode.SelectSingleNode("meopname").InnerText;//工序名
                var meopno = docnode.SelectSingleNode("meopno").InnerText;//工序号
                //var part_id = docnode.SelectSingleNode("part_id").InnerText;//零部件ID
                var partname = docnode.SelectSingleNode("partname").InnerText;//零部件名称
                var partrevision = docnode.SelectSingleNode("part_revision_id").InnerText;//零部件版本
                var partno = docnode.SelectSingleNode("partno").InnerText;//零件图号
                var material_mark = docnode.SelectSingleNode("ly2material_mark").InnerText;//加工材料
                var control_type = docnode.SelectSingleNode("ly2control_type").InnerText;//控制系统
                var isthree = docnode.SelectSingleNode("ly2isthree").InnerText;//是否三轴以上数控铣加工
                var istypical = docnode.SelectSingleNode("ly2istypical").InnerText;//是否关键工序
                var factoryid = OracleHelper.GetSingle(string.Format("select factoryid from factory where factoryName='{0}'", ly2plant));
                if (meopno.Contains("&"))
                {
                    string specnoStr = string.Empty;
                    foreach (var specno in meopno.Split('&'))
                    {
                        specnoStr += specno.PadLeft(4, '0') + "&";
                    }
                    meopno = specnoStr.TrimEnd('&');
                }
                else { meopno = meopno.PadLeft(4, '0'); }
                //if (factoryid == null)
                //{
                //    LogHelp.WriteLog("处理数控程序" + xmlPath + "失败:查询不到分厂:" + ly2plant);
                //    LogHelp.WriteOrcale("PDMTOMES_NC" + "@^" + "处理数控程序" + xmlPath + "失败:查询不到分厂【" + ly2plant + "】@^" + "" + "@^" + Convert.ToString(Guid.NewGuid()));
                //    return;
                //}
                var workflowSQL = @"SELECT w.WORKFLOWID,w.PROCESS_NO,w.WORKFLOWREVISION,ws.WORKFLOWSTEPNAME,S.SPECID,S.SPECNO,SB.SPECNAME 
                                    FROM WORKFLOW w 
                                    LEFT JOIN WORKFLOWSTEP ws ON ws.WORKFLOWID =w.WORKFLOWID 
                                    LEFT JOIN SPECBASE SB_ ON SB_.SPECBASEID = NVL(WS.SPECBASEID, WS.SUBWORKFLOWBASEID)
		                            LEFT JOIN SPEC S ON S.SPECID = NVL(SB_.REVOFRCDID,WS.SPECID)
		                            LEFT JOIN SPECBASE SB ON SB.SPECBASEID = S.SPECBASEID
		                            WHERE w.WORKFLOWREVISION ='{0}' AND w.PROCESS_NO ='{1}'";
                var wDT = OracleHelper.Query(string.Format(workflowSQL, ly2process_rev, ly2process_no)).Tables[0];
                var workflowid = string.Empty;
                var specid = string.Empty;
                //if (wDT.Rows.Count == 0)
                //{//查询不到对应的【工艺规程编号、工艺规程版本】
                //    LogHelp.WriteLog("处理数控程序" + xmlPath + "失败:查询不到对应的【工艺规程编号：" + ly2process_no + "、工艺规程版本:" + ly2process_rev);
                //    LogHelp.WriteOrcale("PDMTOMES_NC" + "@^" + "处理数控程序" + xmlPath + "失败:查询不到对应的【工艺规程编号：" + ly2process_no + "、工艺规程版本:" + ly2process_rev + "】@^" + "" + "@^" + Convert.ToString(Guid.NewGuid()));
                //    return;
                //}
                //else
                if (wDT.Rows.Count > 0)
                {
                    workflowid = wDT.Rows[0]["WORKFLOWID"].ToString();
                    DataRow[] row = wDT.Select("SPECNO='" + meopno + "' and SPECNAME='" + meopname + "'");
                    if (row.Length > 0)
                    {
                        specid = row[0]["SPECID"].ToString();
                    }
                }
                var ncDT = OracleHelper.Query(string.Format(selectNC, ly2nc_no, ly2process_no, ly2process_rev)).Tables[0];
                if (ncDT.Rows.Count > 0)
                {
                    LogHelp.WriteLog("处理数控程序" + xmlPath + ":数控程序编号:" + ly2nc_no + "工艺规程编号：" + ly2process_no + "、工艺规程版本:" + ly2process_rev + "已存在");
                    LogHelp.WriteOrcale("PDMTOMES_NC" + "@^" + "处理数控程序" + xmlPath + ":【数控程序编号:" + ly2nc_no + "工艺规程编号：" + ly2process_no + "、工艺规程版本:" + ly2process_rev + "】已存在@^" + "" + "@^" + Convert.ToString(Guid.NewGuid()));
                    //return;
                    uuid = ncDT.Rows[0]["ID"].ToString();
                    OracleHelper.ExecuteSql(string.Format(@"delete from ncprogramdetaile where parentid='{0}'", uuid));//存在，先删除明细
                }
                else
                {
                    arrList.Add(string.Format(insertNC, uuid, ly2nc_no, object_name, factoryid, ly2process_no, ly2process_rev, meopname, meopno, partno, partrevision, partname, partno, material_mark, control_type, isthree, istypical));
                }
                XmlNode EQUIPS = docnode.SelectSingleNode("EQUIPS");//设备
                if (EQUIPS.ChildNodes.Count > 0)
                {
                    foreach (XmlNode node in EQUIPS.ChildNodes)
                    {
                        var equip_code = node.SelectSingleNode("equip_code").InnerText;
                        var ncdDT = OracleHelper.Query(string.Format(selectNCD, uuid, equip_code)).Tables[0];
                        if (ncdDT.Rows.Count > 0)
                        {
                            LogHelp.WriteLog("处理数控程序" + xmlPath + ":数控程序编号:" + ly2nc_no + "工艺规程编号：" + ly2process_no + "、工艺规程版本:" + ly2process_rev + "下的设备【" + equip_code + "】已存在");
                            LogHelp.WriteOrcale("PDMTOMES_NC" + "@^" + "处理数控程序" + xmlPath + ":【数控程序编号:" + ly2nc_no + "工艺规程编号：" + ly2process_no + "、工艺规程版本:" + ly2process_rev + "下的设备【" + equip_code + "】已存在@^" + "" + "@^" + Convert.ToString(Guid.NewGuid()));
                            continue;
                        }
                        arrList.Add(string.Format(insertNCD, uuid, equip_code, node.SelectSingleNode("equip_xh").InnerText, null, null));
                    }
                }
                var DocPath = ConfigurationManager.AppSettings["NCFilesPath"];
                DocPath += @"\" + ly2process_no + "-" + ly2process_rev + "-" + meopno;
                XmlNode Documents = docnode.SelectSingleNode("Documents");//附件
                if (Documents.ChildNodes.Count > 0)
                {
                    foreach (XmlNode node in Documents.ChildNodes)
                    {
                        var fileName = node.InnerText;
                        var filePath = DocPath + @"\" + fileName;
                        if (File.Exists(filePath))
                        {
                            var filePath2 = @"Temp/NCFiles/" + ly2process_no + "-" + ly2process_rev + "-" + meopno + @"/" + fileName;
                            var docDT = OracleHelper.Query(string.Format(selectDoc, string.IsNullOrWhiteSpace(specid) ? workflowid : specid, fileName, filePath2)).Tables[0];
                            //if (docDT.Rows.Count > 0)
                            //{
                            //    LogHelp.WriteLog("处理数控程序" + xmlPath + ":数控程序编号:" + ly2nc_no + "工艺规程编号：" + ly2process_no + "、工艺规程版本:" + ly2process_rev + "下的文件【" + fileName + "】已存在");
                            //    LogHelp.WriteOrcale("PDMTOMES_NC" + "@^" + "处理数控程序" + xmlPath + ":【数控程序编号:" + ly2nc_no + "工艺规程编号：" + ly2process_no + "、工艺规程版本:" + ly2process_rev + "】下的文件【" + fileName + "】已存在@^" + "" + "@^" + Convert.ToString(Guid.NewGuid()));
                            //    continue;
                            //}
                            var docDT2 = OracleHelper.Query(string.Format(selectNCD2, uuid, fileName, filePath2)).Tables[0];
                            if (docDT2.Rows.Count == 0)
                            {
                                arrList.Add(string.Format(insertNCD, uuid, null, null, fileName, filePath2));
                            }
                            var parentid = string.IsNullOrWhiteSpace(specid) ? workflowid : specid;
                            if (!string.IsNullOrWhiteSpace(parentid) && docDT.Rows.Count == 0)
                            {
                                arrList.Add(string.Format(insertDoC, parentid, fileName, filePath2));
                            }
                        }
                        else
                        {
                            LogHelp.WriteLog("附件【" + fileName + "】在路径【" + DocPath + "】下查询不到");
                        }
                    }
                }
                OracleHelper.ExecuteSqlTran(arrList);
                LogHelp.WriteLog("处理数控程序" + xmlPath + "成功:");
                LogHelp.WriteOrcale("PDMTOMES_NC" + "@^" + "处理数控程序" + xmlPath + "成功@^" + "" + "@^" + Convert.ToString(Guid.NewGuid()));
            }
            catch (Exception ex)
            {
                LogHelp.WriteLog("处理数控程序" + xmlPath + "异常:" + ex.Message);
                LogHelp.WriteOrcale("PDMTOMES_NC" + "@^" + "处理数控程序" + xmlPath + "异常:" + ex.Message + "@^" + "" + "@^" + Convert.ToString(Guid.NewGuid()));
            }

        }

        #endregion

        #region "特殊过程报告 add by longb 2205-05-15"
        [WebMethod]
        public string UFC_Get_TCToMES_TSGC_Service(string strMessage)
        {
            LogHelp.SetConfig();
            LogHelp.WriteLog("特殊过程接收到的：strMessage " + strMessage);
            XmlDocument myxml = new XmlDocument();
            myxml.LoadXml(strMessage);
            string strSpecialProcessNo = "";
            string strFileVersion = "";
            string strFileName = "";
            string strBatchVersion = "";
            string strPeriod = "";//
            string strPlant = "";
            string strIndate = "";
            try
            {
                XmlNode docnode = myxml.SelectSingleNode("Root/LY2TSGC");
                if (docnode.SelectSingleNode("itemrev_id") != null)
                {
                    strFileVersion = docnode.SelectSingleNode("itemrev_id").InnerText;
                }
                if (docnode.SelectSingleNode("object_name") != null)
                {
                    strFileName = docnode.SelectSingleNode("object_name").InnerText;
                }
                if (docnode.SelectSingleNode("bch") != null)
                {
                    strBatchVersion = docnode.SelectSingleNode("bch").InnerText;
                }
                if (docnode.SelectSingleNode("period") != null)
                {
                    strPeriod = docnode.SelectSingleNode("period").InnerText;
                }
                if (docnode.SelectSingleNode("plant") != null)
                {
                    strPlant = docnode.SelectSingleNode("plant").InnerText;
                }
                if (docnode.SelectSingleNode("sxsj") != null)
                {
                    strIndate = docnode.SelectSingleNode("sxsj").InnerText;
                }
                if (docnode.SelectSingleNode("specialprocessno") != null)
                {
                    strSpecialProcessNo = docnode.SelectSingleNode("specialprocessno").InnerText;
                }
                var uuid = Guid.NewGuid().ToString();
                var arrayList = new ArrayList();
                if (!string.IsNullOrWhiteSpace(strSpecialProcessNo))
                {
                    OracleHelper.ExecuteSql(string.Format(@"delete from specialcoursespecreportbank where specialcoursespecreportno='{0}'", strSpecialProcessNo));
                    OracleHelper.ExecuteSql(string.Format(@"delete from specialcoursespeccontent where specialcoursespecreportbankid in (select specialcoursespecreportbankid from specialcoursespecreportbank where specialcoursespecreportno='{0}')", strSpecialProcessNo));
                    var sbankid = OracleHelper.GetSingle(string.Format(@"select specialcoursespecreportbankid from specialcoursespecreportbank where specialcoursespecreportno='{0}' and filename='{1}' and fileversion='{2}'", strSpecialProcessNo, strFileName, strFileVersion));
                    if (sbankid == null)
                    {
                        arrayList.Add(string.Format(@"insert into specialcoursespecreportbank(specialcoursespecreportbankid, specialcoursespecreportno, fileversion, filename, batchversion,indate, period, plant,createdate)
                                                values('{0}','{1}','{2}','{3}','{4}',to_date('{5}','yyyy-MM-dd'),'{6}','{7}',sysdate)", uuid, strSpecialProcessNo, strFileVersion, strFileName, strBatchVersion, strIndate, strPeriod, strPlant));
                    }
                    else
                    {
                        uuid = sbankid.ToString();
                        arrayList.Add(string.Format(@"update specialcoursespecreportbank set indate=to_date('{0}','yyyy-MM-dd'), period='{1}', plant='{2}' where specialcoursespecreportbankid='{3}'", strIndate, strPeriod, strPlant, uuid));
                    }
                }
                else
                {
                    return "<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES_TSGC</SysName><success>0</success><data><![CDATA[接收失败,特殊过程确认编号为空]]></data></header></ReqMsg>";
                }
                foreach (XmlNode node in docnode.ChildNodes)
                {
                    if (node.Name != "Contents") continue;
                    string processtype = "", reportname = "", meopname = "", material = "", remark = "", information = "", drawingno = "", xlh = "", code = "", employeenames = "", resourcenames = "";
                    if (node.SelectSingleNode("processtype") != null)
                    {
                        processtype = node.SelectSingleNode("processtype").InnerText;
                    }
                    if (node.SelectSingleNode("reportname") != null)
                    {
                        reportname = node.SelectSingleNode("reportname").InnerText;
                    }
                    if (node.SelectSingleNode("meopname") != null)
                    {
                        meopname = node.SelectSingleNode("meopname").InnerText;
                    }
                    if (node.SelectSingleNode("material") != null)
                    {
                        material = node.SelectSingleNode("material").InnerText;
                    }
                    if (node.SelectSingleNode("remark") != null)
                    {
                        remark = node.SelectSingleNode("remark").InnerText;
                    }
                    if (node.SelectSingleNode("information_new") != null)
                    {
                        information = node.SelectSingleNode("information_new").InnerText;
                    }
                    if (node.SelectSingleNode("drawingno") != null)
                    {
                        drawingno = node.SelectSingleNode("drawingno").InnerText;
                    }
                    if (node.SelectSingleNode("xlh") != null)
                    {
                        xlh = node.SelectSingleNode("xlh").InnerText;
                    }
                    if (node.SelectSingleNode("code") != null)
                    {
                        code = node.SelectSingleNode("code").InnerText;
                    }
                    if (node.SelectSingleNode("usersid") != null)
                    {
                        employeenames = node.SelectSingleNode("usersid").InnerText;
                    }
                    if (node.SelectSingleNode("equip") != null)
                    {
                        resourcenames = node.SelectSingleNode("equip").InnerText;
                    }
                    var contentid = OracleHelper.GetSingle(string.Format(@"select specialcoursespeccontentid from specialcoursespeccontent where specialcoursespecreportbankid='{0}' and code='{1}'", uuid, code));
                    if (contentid == null)
                    {
                        arrayList.Add(string.Format(@"insert into specialcoursespeccontent(specialcoursespeccontentid,specialcoursespecreportbankid,processtype, reportname, meopname, material, remark, information, drawingno, xlh, code, employeenames, resourcenames)
                                                values(sys_guid(),'{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}')",
                                                        uuid, processtype, reportname, meopname, material, remark, information, drawingno, xlh, code, employeenames, resourcenames));
                    }
                    else
                    {
                        arrayList.Add(string.Format(@"update specialcoursespeccontent set processtype='{0}',reportname='{1}', meopname='{2}', material='{3}', remark='{4}', information='{5}', drawingno='{6}',employeenames='{7}', resourcenames='{8}' where specialcoursespeccontentid='{9}'",
                                                    processtype, reportname, meopname, material, remark, information, drawingno, employeenames, resourcenames, contentid));
                    }
                }
                OracleHelper.ExecuteSqlTran(arrayList);
            }
            catch (Exception ex)
            {
                return "<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES_TSGC</SysName><success>0</success><data><![CDATA[接收处理异常：" + ex.Message + "]]></data></header></ReqMsg>";
            }

            return "<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES_TSGC</SysName><success>1</success><data><![CDATA[接收成功]]></data></header></ReqMsg>";
        }
        #endregion

        #region 工艺更改单--批次暂停接口 add by longb 2025-07-10
        [WebMethod]
        public string PDM_WorkflowChange_Service(string strMessage)
        {
            string Message = string.Empty;
            try
            {
                LogHelp.SetConfig();
                LogHelp.WriteLog("工艺更改接收到的：strMessage " + strMessage);
                XmlDocument myxml = new XmlDocument();
                myxml.LoadXml(strMessage);
                bool result = false;
                XmlNode meops = myxml.SelectSingleNode("ReqMsg/document/mesDocument/Root/Info");
                var ly2GY_ECNNo = meops.SelectSingleNode("ly2GY_ECNNo").InnerText;//工艺更改单号
                var processrev = meops.SelectSingleNode("processrev").InnerText;//工艺规程版本
                var ly2process_no = meops.SelectSingleNode("ly2process_no").InnerText;//工艺规程名称
                var decisionToProduct = meops.SelectSingleNode("ly2decisionToProduct").InnerText;//对产品的决定
                var ly2batch_no = meops.SelectSingleNode("ly2batch_no").InnerText;//批次信息
                if (!decisionToProduct.Equals("无影响"))
                {
                    string strSql = @"select cci.containerid,cci.containername,cci.productid,cci.productname,cci.qty 
                            from containercurrentinfo cci 
                            left join workflow w on w.workflowid =decode(cci.isinstore,1,cci.bsworkflowid,cci.workflowid)
                            left join workflowbase wb on wb.workflowbaseid =w.workflowbaseid 
                            where cci.isinstore=0 and nvl(cci.ishold,0)=0 AND cci.containerstatus <>2";

                    if (!string.IsNullOrWhiteSpace(ly2process_no))
                    {
                        strSql += string.Format(" and w.process_no='{0}' and w.workflowrevision='{1}' ", ly2process_no, processrev);
                    }
                    if (!string.IsNullOrWhiteSpace(ly2batch_no))
                    {
                        strSql += string.Format(" and cci.containername in ('{0}')", ly2batch_no.Replace(",", "','"));
                    }
                    DataTable conDt = OracleHelper.Query(strSql).Tables[0];
                    //暂停所查出的批次
                    ArrayList sqls = new ArrayList();
                    string sql = "update containercurrentinfo set ishold=1 where containerid='{0}'";
                    string sql2 = @"INSERT INTO OperContainerRecord(containerid,containername,productid,productname,operatorid,operreason,qty,createdate,opertype)
                                VALUES('{0}','{1}','{2}','{3}','{4}','{5}',{6},SYSDATE,'2')";
                    foreach (DataRow dr in conDt.Rows)
                    {
                        sqls.Add(string.Format(sql, dr["containerid"].ToString()));
                        sqls.Add(string.Format(sql2, dr["containerid"].ToString(), dr["containername"].ToString(), dr["productid"].ToString(), dr["productname"].ToString(), Guid.NewGuid().ToString(), "工艺变更暂停", dr["qty"].ToString()));
                    }
                    if (sqls.Count > 0)
                    {
                        result = OracleHelper.ExecuteSqlTran(sqls, ref Message);
                        if (result) { Message = "工艺变更接收成功,批次暂停成功"; }
                    }
                    else
                    {
                        Message = "根据工艺变更信息，查询不到需要暂停的批次信息";
                    }
                }
                return @"<?xml version='1.0' encoding='utf-8'?><RespMsg><header><SysName>APP_MES</SysName><success>" + result + "</success><data><![CDATA[" + Message + "]]></data></header></RespMsg>";
            }
            catch (Exception ex)
            {
                Message = ex.Message;
                return @"<?xml version='1.0' encoding='utf-8'?><RespMsg><header><SysName>APP_MES</SysName><success>false</success><data><![CDATA[" + ex.Message + "]]></data></header></RespMsg>";
            }
            finally
            {
                LogHelp.WriteOrcale("PDM_WorkflowChange_Service@^" + Message + "@^" + (strMessage.Replace("\'", "\"").Length > 4000 ? "xml太长" : strMessage.Replace("\'", "\"")) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 2017-8-30
            }
        }
        #endregion

        #region "三定卡片 add by longb 2025-07-14"
        [WebMethod]
        public string UFC_Get_TCToMES_SDKP_Service(string strMessage, Byte[] fileinstance)
        {
            //Byte[] fileinstance=new byte[0];
            LogHelp.SetConfig();
            LogHelp.WriteLog("三定卡片接收到的：strMessage " + strMessage);
            var DocPath = ConfigurationManager.AppSettings["ThreeCardFilesPath"];

            XmlDocument myxml = new XmlDocument();
            myxml.LoadXml(strMessage);
            string strFileName = "";
            string strProcessName = "";
            string strProcessRev = "";
            string strMeopno = "";//工序号

            XmlNode docnode = XMLParse.getNode(myxml, "/ReqMsg/document");
            strFileName = docnode.SelectSingleNode("document").InnerText;
            strProcessName = docnode.SelectSingleNode("process").InnerText;
            if (docnode.SelectSingleNode("processRev") != null)
            {
                strProcessRev = docnode.SelectSingleNode("processRev").InnerText;
                strMeopno = docnode.SelectSingleNode("meopno") == null ? "" : docnode.SelectSingleNode("meopno").InnerText;
            }
            //推送的如果是附件，则另存
            LogHelp.WriteOrcale("PDMTOMES_ThreeCard" + "@^" + "接收到附件" + strFileName + "@^" + "" + "@^" + Convert.ToString(Guid.NewGuid()));
            DocPath += @"\" + strProcessName + "-" + strProcessRev + "-" + strMeopno;
            LogHelp.WriteLog("三定卡片接收附件：" + strFileName + "文件大小：" + fileinstance.Length.ToString().Trim());
            if (!Directory.Exists(DocPath))
            {
                Directory.CreateDirectory(DocPath);
            }
            DocPath += @"\" + strFileName;
            FileStream fs = null;
            try
            {
                if (File.Exists(DocPath))
                {
                    var Minutes = 0;
                    try
                    {
                        Minutes = (DateTime.Now - File.GetLastWriteTime(DocPath)).Minutes;
                    }
                    catch (Exception ex) { }
                    if (Minutes > 5)
                    {
                        File.Delete(DocPath);
                        fs = new FileStream(DocPath, FileMode.OpenOrCreate);
                    }
                    else
                    {
                        fs = new FileStream(DocPath, FileMode.Append);
                    }
                }
                else
                {
                    fs = new FileStream(DocPath, FileMode.OpenOrCreate);
                }

                byte[] Buffer = fileinstance;
                fs.Write(Buffer, 0, Buffer.Length);
                fs.Flush();
            }
            catch (Exception ex)
            {
                LogHelp.WriteLog("接收附件【" + strFileName + "】失败");

                return @"<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES_SDKP</SysName><success>0</success><data><![CDATA[接收附件【" + strFileName + "】失败:" + ex.Message + "]]></data></header></ReqMsg>";
            }
            finally
            {
                fs.Close();
            }
            //如果是.xml文件，读取处理写入数据库
            if (strFileName.Contains(".xml"))
            {
                DealThreeCardData(DocPath);
            }
            return "<?xml version='1.0' encoding='utf-8'?><ReqMsg><header><SysName>APP_MES_SDKP</SysName><success>1</success><data><![CDATA[接收附件【" + strFileName + "】成功]]></data></header></ReqMsg>";
        }
        [WebMethod]
        public void DealThreeCardData(string xmlPath)
        {
            try
            {
                var arrList = new ArrayList();
                var insertTC = @"insert into threefixedcards
                                (id, cardcode, cardname, factoryid, workflowname, workflowversion, specname, specno, productname, productdesc, publishplant, workcenter, secret, bmqx, dmyj, zxfw,createdate)
                                values('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}', '{10}', '{11}', '{12}', '{13}', '{14}', '{15}',sysdate)";
                var insertTCD = @"insert into threefixedcarddetail(id, parentid, code, name, worktype,threetype)
                                values(sys_guid(),'{0}', '{1}', '{2}', '{3}', '{4}')";
                var selectTC = @"select * from threefixedcards tc where tc.cardcode ='{0}'";
                var selectSR = @"select * from specresourceinfo s where s.specid ='{0}'";
                var deleteSR = @"delete from specresourceinfo s where s.specid ='{0}'";//根据【specid】删除工序设备管理表
                var insertSR = @"insert into specresourceinfo(specresourceinfoid,resourceid,specid)values(sys_guid(), '{0}', '{1}')";
                var selectR = @"select r.resourceid from resourcedef r where r.resourcename ='{0}'";

                var uuid = Guid.NewGuid().ToString();

                XmlDocument myxml = new XmlDocument();
                myxml.Load(xmlPath);
                XmlNode docnode = XMLParse.getNode(myxml, "/Root/LY2DECISION");
                var ly2cardcode = docnode.SelectSingleNode("ly2cardcode").InnerText;//卡片编号
                var object_name = docnode.SelectSingleNode("object_name").InnerText;//卡片名称
                var ly2plant = docnode.SelectSingleNode("ly2plant").InnerText;//单位(分厂)
                var ly2gygcbh = docnode.SelectSingleNode("ly2gygcbh").InnerText;//工艺规程编号
                var ly2gygcbb = docnode.SelectSingleNode("ly2gygcbb").InnerText;//工艺规程版本
                var meopname = docnode.SelectSingleNode("ly2meopname").InnerText;//工序名
                var meopno = docnode.SelectSingleNode("ly2meopno").InnerText;//工序号
                var ly2partno = docnode.SelectSingleNode("ly2partno").InnerText;//零件号
                var ly2partname = docnode.SelectSingleNode("ly2partname").InnerText;//零部件名称
                var ly2publishplant = docnode.SelectSingleNode("ly2publishplant").InnerText;//发放单位
                var ly2workcenter = docnode.SelectSingleNode("ly2workcenter").InnerText;//工作中心
                var secret = docnode.SelectSingleNode("secret").InnerText;//密级
                var ly2bmqx = docnode.SelectSingleNode("ly2bmqx").InnerText;//保密期限
                var ly2dmyj = docnode.SelectSingleNode("ly2dmyj").InnerText;//定密依据
                var ly2zzfw = docnode.SelectSingleNode("ly2zzfw").InnerText;//知悉范围
                var factoryid = OracleHelper.GetSingle(string.Format("select factoryid from factory where factoryName='{0}'", ly2plant));
                var workflowSQL = @"SELECT w.WORKFLOWID,w.PROCESS_NO,w.WORKFLOWREVISION,ws.WORKFLOWSTEPNAME,S.SPECID,S.SPECNO,SB.SPECNAME 
                                    FROM WORKFLOW w 
                                    LEFT JOIN WORKFLOWSTEP ws ON ws.WORKFLOWID =w.WORKFLOWID 
                                    LEFT JOIN SPECBASE SB_ ON SB_.SPECBASEID = NVL(WS.SPECBASEID, WS.SUBWORKFLOWBASEID)
		                            LEFT JOIN SPEC S ON S.SPECID = NVL(SB_.REVOFRCDID,WS.SPECID)
		                            LEFT JOIN SPECBASE SB ON SB.SPECBASEID = S.SPECBASEID
		                            WHERE w.WORKFLOWREVISION ='{0}' AND w.PROCESS_NO ='{1}'";
                var wDT = OracleHelper.Query(string.Format(workflowSQL, ly2gygcbb, ly2gygcbh)).Tables[0];
                var workflowid = string.Empty;
                var specid = string.Empty;
                if (wDT.Rows.Count > 0)
                {
                    workflowid = wDT.Rows[0]["WORKFLOWID"].ToString();
                    DataRow[] row = wDT.Select("SPECNO='" + meopno + "' and SPECNAME='" + meopname + "'");
                    if (row.Length > 0)
                    {
                        specid = row[0]["SPECID"].ToString();
                    }
                }
                var ncDT = OracleHelper.Query(string.Format(selectTC, ly2cardcode)).Tables[0];
                if (ncDT.Rows.Count > 0)
                {
                    LogHelp.WriteLog("处理三定卡片" + xmlPath + ":卡片编号:" + ly2cardcode + "工艺规程编号：" + ly2gygcbh + "、工艺规程版本:" + ly2gygcbb + "已存在");
                    LogHelp.WriteOrcale("PDMTOMES_ThreeCard" + "@^" + "处理三定卡片" + xmlPath + ":【卡片编号:" + ly2cardcode + "工艺规程编号：" + ly2gygcbh + "、工艺规程版本:" + ly2gygcbb + "】已存在@^" + "" + "@^" + Convert.ToString(Guid.NewGuid()));
                    //return;
                    uuid = ncDT.Rows[0]["ID"].ToString();
                    OracleHelper.ExecuteSql(string.Format(@"delete from threefixedcarddetail where parentid='{0}'", uuid));//存在，先删除明细
                }
                else
                {
                    arrList.Add(string.Format(insertTC, uuid, ly2cardcode, object_name, factoryid, ly2gygcbh, ly2gygcbb, meopname, meopno, ly2partno, ly2partname, ly2publishplant, ly2workcenter, secret, ly2bmqx, ly2dmyj, ly2zzfw));
                }

                XmlNode OPERATORS = docnode.SelectSingleNode("OPERATORS");//操作工
                if (OPERATORS.ChildNodes.Count > 0)
                {
                    var ouserids = string.Empty;
                    foreach (XmlNode node in OPERATORS.ChildNodes)
                    {
                        if (node.SelectSingleNode("ouserid") == null) { continue; }
                        var ouserid = node.SelectSingleNode("ouserid").InnerText;
                        var ousername = node.SelectSingleNode("ousername").InnerText;
                        var oworktype = node.SelectSingleNode("oworktype").InnerText;
                        if (ouserids.Contains(ouserid)) { continue; }
                        arrList.Add(string.Format(insertTCD, uuid, ouserid, ousername, oworktype, "0"));
                        ouserids += ouserid + ",";
                    }
                }

                XmlNode INSPECTORS = docnode.SelectSingleNode("INSPECTORS");//检验员
                if (INSPECTORS.ChildNodes.Count > 0)
                {
                    var iuserids = string.Empty;
                    foreach (XmlNode node in INSPECTORS.ChildNodes)
                    {
                        if (node.SelectSingleNode("iuserid") == null) { continue; }
                        var iuserid = node.SelectSingleNode("iuserid").InnerText;
                        var iusername = node.SelectSingleNode("iusername").InnerText;
                        var iworktype = node.SelectSingleNode("iworktype").InnerText;
                        if (iuserids.Contains(iuserid)) { continue; }
                        arrList.Add(string.Format(insertTCD, uuid, iuserid, iusername, iworktype, "1"));
                        iuserids += iuserid + ",";
                    }
                }

                XmlNode EQUIPS = docnode.SelectSingleNode("EQUIPS");//设备
                if (EQUIPS.ChildNodes.Count > 0)
                {
                    var equip_codes = string.Empty;
                    var srDT = OracleHelper.Query(string.Format(selectSR, specid)).Tables[0];
                    if (!string.IsNullOrWhiteSpace(specid) && srDT.Rows.Count > 0)
                    {//工序不为空，删除工序下维护的设备信息
                        arrList.Add(string.Format(deleteSR, specid));
                        LogHelp.WriteLog("处理三定卡片,删除工序【" + meopno + "-" + meopname + "】下维护的旧设备信息:" + JsonConvert.SerializeObject(srDT));
                    }
                    foreach (XmlNode node in EQUIPS.ChildNodes)
                    {
                        if (node.SelectSingleNode("equip_code") == null) { continue; }
                        var equip_code = node.SelectSingleNode("equip_code").InnerText;
                        var equip_name = node.SelectSingleNode("equip_name").InnerText;
                        var equip_xh = node.SelectSingleNode("equip_xh").InnerText;
                        if (equip_codes.Contains(equip_code)) { continue; }
                        arrList.Add(string.Format(insertTCD, uuid, equip_code, equip_name, equip_xh, "2"));
                        var rDT = OracleHelper.Query(string.Format(selectR, equip_code)).Tables[0];
                        if (rDT.Rows.Count > 0)
                        {
                            arrList.Add(string.Format(insertSR, rDT.Rows[0]["resourceid"], specid));
                        }
                        else
                        {//设备在MES中没有维护，则先新增再绑定
                            var strMessage = string.Empty;
                            var result = erpMethod.SaveResourceData(equip_code, equip_xh, ly2plant, ly2workcenter, ref strMessage);
                            if (result)
                            {
                                var rDT2 = OracleHelper.Query(string.Format(selectR, equip_code)).Tables[0];
                                if (rDT2.Rows.Count > 0)
                                {
                                    arrList.Add(string.Format(insertSR, rDT2.Rows[0]["resourceid"], specid));
                                }
                            }
                            LogHelp.WriteLog("处理三定卡片,MES工序【" + meopno + "-" + meopname + "】下的设备编码:" + equip_code + "不存在;" + (result ? "" : "新增写入结果：" + strMessage));
                        }
                        equip_codes += equip_code + ",";
                    }
                }
                var DocPath = ConfigurationManager.AppSettings["ThreeCardFilesPath"];
                DocPath += @"\" + ly2gygcbh + "-" + ly2gygcbb + "-" + meopno;
                XmlNode Documents = docnode.SelectSingleNode("Documents");//附件
                if (Documents.ChildNodes.Count > 0)
                {
                    foreach (XmlNode node in Documents.ChildNodes)
                    {
                        var fileName = node.InnerText;
                        var filePath = DocPath + @"\" + fileName;
                        if (File.Exists(filePath))
                        {
                            var filePath2 = @"Temp/ThreeCardFiles/" + ly2gygcbh + "-" + ly2gygcbb + "-" + meopno + @"/" + fileName;
                            arrList.Add(string.Format(insertTCD, uuid, filePath2, fileName, "", "3"));
                        }
                        else
                        {
                            LogHelp.WriteLog("附件【" + fileName + "】在路径【" + DocPath + "】下查询不到");
                        }
                    }
                }
                OracleHelper.ExecuteSqlTran(arrList);
                LogHelp.WriteLog("处理三定卡片" + xmlPath + "成功:");
                LogHelp.WriteOrcale("PDMTOMES_ThreeCard" + "@^" + "处理三定卡片" + xmlPath + "成功@^" + "" + "@^" + Convert.ToString(Guid.NewGuid()));
            }
            catch (Exception ex)
            {
                LogHelp.WriteLog("处理三定卡片" + xmlPath + "异常:" + ex.Message);
                LogHelp.WriteOrcale("PDMTOMES_ThreeCard" + "@^" + "处理三定卡片" + xmlPath + "异常:" + ex.Message + "@^" + "" + "@^" + Convert.ToString(Guid.NewGuid()));
            }

        }
        #endregion

        #region MES和ERP配套单下发接口 add zhunan 2025.9.23
        [WebMethod]
        public string ERP_Send_Bom_Component_Service(string strMessage)
        {
            log4net.Config.XmlConfigurator.Configure();
            ERPSendMESDataMethod erpMethod = new ERPSendMESDataMethod();
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(strMessage);

                string orderName = xmlDoc.SelectSingleNode("//document/AUFNR").InnerText;//生产订单号
                string RSNUM = xmlDoc.SelectSingleNode("//document/RSNUM").InnerText;//预留业务号

                XmlNodeList itemNodes = xmlDoc.SelectNodes("//document/Items/Item");

                if (itemNodes.Count == 0)
                {
                    LogHelp.WriteLog(string.Format("订单:['{0}']缺少组件信息", orderName));
                    return @"<?xml version='1.0' encoding='utf-8'?><RespMsg><RTYPE>E</RTYPE><RTMSG>订单缺少组件信息</RTMSG></RespMsg>";
                }

                string sql = string.Format(@"SELECT * FROM mfgorder t WHERE t.mfgordername = '{0}'", orderName);
                DataSet ds = OracleHelper.Query(sql);
                if (ds.Tables[0].Rows.Count == 0)
                {
                    LogHelp.WriteLog(string.Format("订单:['{0}']在MES系统中不存在", orderName));
                    return @"<?xml version='1.0' encoding='utf-8'?><RespMsg><RTYPE>E</RTYPE><RTMSG>订单在MES中不存在</RTMSG></RespMsg>";
                }

                Dictionary<string, string> para = new Dictionary<string, string>();
                para["mfgordername"] = orderName;

                DataTable dtDiff = erpMethod.GetBomInfo(orderName);
                foreach (XmlNode xn in itemNodes)
                {
                    if (xn.Name != "Item") { continue; }

                    Dictionary<string, string> dict = new Dictionary<string, string>();
                    dict.Add("MFGORDERNAME", orderName);//订单号
                    dict.Add("RSNUM", RSNUM);//预留业务号

                    string productno = xn.SelectSingleNode("MATNR").InnerText;//物料编码
                    erpMethod.erpAndTcProductNameHandle(ref productno);
                    dict.Add("PRODUCTNAME", productno);

                    string qty = xn.SelectSingleNode("BDMNG").InnerText;//发出数量
                    dict.Add("QTY", qty);

                    string uom = xn.SelectSingleNode("MEINS").InnerText;//计量单位
                    dict.Add("UOM", uom);

                    var containerflag = xn.SelectSingleNode("CHARG");//零件批次号
                    dict.Add("PRODUCTBATCHNO", containerflag == null ? "" : containerflag.InnerText);

                    var specno = xn.SelectSingleNode("VORNR");//工序号
                    dict.Add("SPECNO", specno == null ? "" : specno.InnerText);

                    var RSPOS = xn.SelectSingleNode("RSPOS");//预定的项目编号
                    dict.Add("RSPOS", RSPOS == null ? "" : RSPOS.InnerText);

                    var SCHGT = xn.SelectSingleNode("SCHGT");//散装物料标识
                    dict.Add("SCHGT", SCHGT == null ? "" : SCHGT.InnerText);

                    var DUMPS = xn.SelectSingleNode("DUMPS");//虚拟项目标识
                    dict.Add("DUMPS", DUMPS == null ? "" : DUMPS.InnerText);

                    var LGORT = xn.SelectSingleNode("LGORT");//库存地点
                    dict.Add("LGORT", LGORT == null ? "" : LGORT.InnerText);

                    var LIFNR = xn.SelectSingleNode("LIFNR");//供应商编码
                    dict.Add("LIFNR", LIFNR == null ? "" : LIFNR.InnerText);

                    string filter = string.Format("mfgordername = '{0}' AND productname = '{1}' AND specno = '{2}'", orderName, productno, dict["SPECNO"]);
                    DataRow[] drList = dtDiff.Select(filter);

                    dict.Add("SPECNAME", drList.Length > 0 ? drList[0]["opdesc"].ToString() : "");//工序名称
                    dict.Add("bomid", drList.Length > 0 ? drList[0]["bomid"].ToString() : "");//bomid

                    string message = erpMethod.SaveErpSendMaterial(dict);
                    if (message == "重复推送订单")
                    {
                        LogHelp.WriteLog(string.Format("ERP配套单下发接口，重复推送订单:{0}", orderName));
                        return @"<?xml version='1.0' encoding='utf-8'?><RespMsg><RTYPE>E</RTYPE><RTMSG>重复推送订单</RTMSG></RespMsg>";
                    }

                    //MES中工艺没有bom时，不执行bom校准
                    if (dtDiff.Rows.Count > 0)
                    {
                        erpMethod.SaveMesSendErpDiff(para);
                        LogHelp.WriteLog(string.Format("ERP配套单下发接口，订单：【{0}】零件：【{1}】工序号：【{2}】{3}", orderName, productno, specno, message));
                    }
                }
                return @"<?xml version='1.0' encoding='utf-8'?><RespMsg><RTYPE>S</RTYPE><RTMSG>MES接收成功</RTMSG></RespMsg>";
            }
            catch (Exception ex)
            {
                LogHelp.WriteError("接收失败" + strMessage, ex);
                return @"<?xml version='1.0' encoding='utf-8'?><RespMsg><RTYPE>E</RTYPE><RTMSG>" + "MES接收失败," + ex.Message + "</RTMSG></RespMsg>";
            }
        }
        #endregion

        [WebMethod]
        public string test()
        {
            return "";
        }

        #region 本地环境模拟ERP返回MES完整BOM信息接口，供本地windows服务调用，服务器不部署该接口 add zhunan 2025.10.15
        [WebMethod]
        public string ERP_Receive_MES_BOM_Diff(string strMessage)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(strMessage);
            string orderName = xmlDoc.SelectSingleNode("//document/AUFNR").InnerText;//生产订单号

            string sql = @"
SELECT mfg.mfgorderid,mfg.mfgordername,mfg.plannedstartdate,pb3.productname mfgproductname,
       mfg.plannedcompletiondate,sb2.specname,s.specno,s.opdesc,s.specid,pbn.productname,
       b.bomid,bb.bomname,pml.qtyrequired,mfg.qty mfgqty,
       (pml.qtyrequired * mfg.qty) mesqty,u.uomname
FROM mfgorder mfg
--查订单件号信息
LEFT JOIN productbase pb2 ON pb2.productbaseid = mfg.productbaseid
LEFT JOIN product p2 ON p2.productid = NVL(pb2.revofrcdid,mfg.productid)
LEFT JOIN productbase pb3 ON pb3.productbaseid=p2.productbaseid
--查件号默认工艺信息
LEFT JOIN workflowbase wfb ON wfb.workflowbaseid = p2.workflowbaseid
LEFT JOIN workflow wf ON wf.workflowid = NVL(wfb.revofrcdid,p2.workflowid)
--bom信息
INNER JOIN bom b ON b.workflowid = wf.workflowid
LEFT JOIN bombase bb ON bb.bombaseid = b.bombaseid
LEFT JOIN productmateriallistitem pml ON pml.bomid = b.bomid
--bom工序信息
LEFT JOIN specbase sb ON sb.specbaseid=pml.specbaseid
LEFT JOIN spec s ON  s.specid=NVL(sb.revofrcdid, pml.specid)
LEFT JOIN specbase sb2 ON sb2.specbaseid = s.specbaseid
--子零件信息
LEFT JOIN productbase pb ON pb.productbaseid = pml.productbaseid
LEFT JOIN product p ON p.productid =NVL(pb.revofrcdid, pml.productid)
LEFT JOIN productbase pbn ON pbn.productbaseid=p.productbaseid
LEFT JOIN uom u ON u.uomid = pml.uomid
WHERE mfg.mfgordername = '{0}'";
            sql = string.Format(sql, orderName);
            DataTable dtBOM = OracleHelper.Query(sql).Tables[0];

            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
            XmlNode rootNode = doc.CreateElement("root");

            //返回消息
            XmlNode RESPMSG = doc.CreateElement("RESPMSG");

            XmlNode RTYPE = doc.CreateElement("RTYPE");
            RTYPE.InnerText = "S";
            //RTYPE.InnerText = "E";
            RESPMSG.AppendChild(RTYPE);

            XmlNode RTMSG = doc.CreateElement("RTMSG");
            RTMSG.InnerText = "接收成功";
            //RTMSG.InnerText = "接收失败";
            RESPMSG.AppendChild(RTMSG);

            rootNode.AppendChild(RESPMSG);

            XmlNode documentNode = doc.CreateElement("document");

            XmlNode AUFNR = doc.CreateElement("AUFNR");
            AUFNR.InnerText = orderName;

            XmlNode RSNUM = doc.CreateElement("RSNUM");
            RSNUM.InnerText = Guid.NewGuid().ToString();

            documentNode.AppendChild(AUFNR);
            documentNode.AppendChild(RSNUM);

            XmlNode ItemsNode = doc.CreateElement("Items");
            foreach (DataRow dr in dtBOM.Rows)
            {
                XmlNode ItemNode = doc.CreateElement("Item");

                //物料编码
                XmlNode MATNR = doc.CreateElement("MATNR");
                MATNR.InnerText = dr["productname"].ToString();
                ItemNode.AppendChild(MATNR);

                //差异数量
                XmlNode BDMNG = doc.CreateElement("BDMNG");
                BDMNG.InnerText = dr["mesqty"].ToString();
                ItemNode.AppendChild(BDMNG);

                //计量单位
                XmlNode MEINS = doc.CreateElement("MEINS");
                MEINS.InnerText = dr["uomname"].ToString();
                ItemNode.AppendChild(MEINS);

                //批次号
                XmlNode CHARG = doc.CreateElement("CHARG");
                CHARG.InnerText = "2501";
                ItemNode.AppendChild(CHARG);

                //工序号
                XmlNode VORNR = doc.CreateElement("VORNR");
                VORNR.InnerText = dr["specno"].ToString();
                ItemNode.AppendChild(VORNR);

                //项目编号
                XmlNode RSPOS = doc.CreateElement("RSPOS");
                RSPOS.InnerText = Guid.NewGuid().ToString();
                ItemNode.AppendChild(RSPOS);

                //散装物料标识
                XmlNode SCHGT = doc.CreateElement("SCHGT");
                SCHGT.InnerText = "散装物料标识";
                ItemNode.AppendChild(SCHGT);

                //虚拟项目标识
                XmlNode DUMPS = doc.CreateElement("DUMPS");
                DUMPS.InnerText = "虚拟项目标识";
                ItemNode.AppendChild(DUMPS);

                //库存地点
                XmlNode LGORT = doc.CreateElement("LGORT");
                LGORT.InnerText = Guid.NewGuid().ToString();
                ItemNode.AppendChild(LGORT);

                //供应商编码
                XmlNode LIFNR = doc.CreateElement("LIFNR");
                LIFNR.InnerText = Guid.NewGuid().ToString();
                ItemNode.AppendChild(LIFNR);

                ItemsNode.AppendChild(ItemNode);
            }

            documentNode.AppendChild(ItemsNode);
            rootNode.AppendChild(documentNode);
            doc.AppendChild(rootNode);

            return doc.InnerXml;
        }
        #endregion
    }
}